Select your Language

Salesforce Trigger Notes


    Triggers :
    -------------
    a. Trigger is an automated action that will be fired when a DML operation is performed on a record.
    b. DML operation can be insert ,update ,upsert ,delete ,merge or undelete
    c. Triggers are classified into two types

    1. Before Triggers
    2. After Triggers

    . Before Triggers :
    1. These are operations which are fired before the data is saved to sobject.
    2. Example :
    Before Insert
    Before Update
    Before Delete

      After Triggers :
    1. These are the operations that are fired after the data is saved to the database.
    2. Example :
    After Insert
    After Update
    After Delete
    After Undelete
 
      Trigger events :
    a. There the events which are going to fire the triggers.
    b. Before Insert ,Before Update ,Before Delete,After Insert ,After Update ,After Delete
       After undelete.
 
     g. Syntax :
    trigger triggerName  on Sobject(event){
 
    }
 
      Example :
    trigger example on Account(before insert){
    }
 
    trigger example on Contact(before insert, after update){
 
    }
 
    Example: Create a before insert trigger on Contact
    trigger example on Contact(before Insert){
 
    }
    Example: Create after delete trigger on Opportunity
    trigger demo on Opportunity (after delete){
 
    }
 
    Example: Create after insert, after delete trigger on Case
    trigger example on Case( after insert ,after delete ){
 
    }
    Example : Create after delete ,after undelete ,after insert trigger on Account.
    trigger example on Account(after insert,after delete ,after undelete){
 
    }
 
=======================================================================
Trigger execution  and statement execution

1. The original record is loaded from the database (or initialized for an insert statement)
2. The new record field values are loaded from the request and overwrite the old values
3. Run system validation (valid field formate, max field length, required value) if the request comes from UI
3 Run all custom validation
3. All before triggers execute (TRIGGERS)
4. System validation occurs, such as verifying that all required fields have a non-null value, and running any user-defined validation rules (VALIDATIONS)
5. The record is saved to the database, but not yet committed
6. All after triggers execute
7. Assignment rules execute
8. Auto-response rules execute
9. Workflow rules execute (WORKFLOW)
10. If there are workflow field updates, the record is updated again
11. If the record was updated with workflow field updates, before and after triggers fire one more time (and only one more time)
12. Escalation rules execute
13. All DML operations are committed to the database
14. Post-commit logic executes, such as sending email



========================================================================




    Triggers:
    ---------
    1. Triggers are automated processes.
    2. Triggers will be fired when a DML operation (Insert, Update, Delete, UnDelete,Merge,Upsert) is performed on the Sobject.
    3. Triggers are classified into two types.
    a. Before Triggers
    b. After Triggers
    4. Before Triggers :
    a. These triggers are fired before the new data is saved to sobject.
 
    5. After Triggers :
    a. These triggers are fired after the new data is saved to soject.
 
    6. Triggers are fired when 7 DML event occur on the object.
    a. Before Insert
    b. Before Update
    c. Before Delete
    d. After Insert
    e. After Update
    f. After Delete
    g. After Undelete
 
    7. Trigger Context Variables :
    a. These are the static variables defind under the standard Apex class Trigger.
    b. These variable stores the data required during the run time of the trigger.
    c. Variables :
    1. isExecuting :
       a. It is a boolean value .
       b. This will return true ,if the current context of apex code is trigger.
   
    2. isBefore  :
       a. It is a boolean value .
       b. This will return true ,if the current context of trigger is before trigger.
 
    3. isAfter  :
       a. It is a boolean value .
       b. This will return true ,if the current context of trigger is after trigger.
 
    4. isInsert :
       a. It is a boolean value .
       b. This will return true ,if the current context of trigger is insert trigger.
 
    5. isUpdate :
       a. It is a boolean value .
       b. This will return true ,if the current context of trigger is update trigger.
 
    6. isDelete :
       a. It is a boolean value .
       b. This will return true ,if the current context of trigger is delete trigger.
 
    7. isUndelete :
       a. It is a boolean value .
       b. This will return true ,if the current context of trigger is Undelete trigger.
 
    8. new   :
       a. It is a list of sobject.
       b. This will store list new records on which we are performing operation.
 
    9. old   :
       a. It is a list of sobject.
       b. This will store list of old version of records on which we are performing operation.
 
    10.oldMap :
       a. It is a Map of records ,where Id of the record is the key and record is the value.
       b. This will contain old version of records
 
    11.NewMap :
       a. It is a Map of records ,where Id of the record is the key and record is the value.
       b. This will contain new version of records
 
    12. size :
    a. This is a integer value.
    b. This will return count of no of records on which we trigger is running
 
    8. Syntax :
    trigger triggerName on Sobject(events){
 
        }
 
    Example :1  Create a before insert trigger on Account
    trigger example on Account(before Insert){
 
    }
 
    Example :2 Create after update trigger on Contact
    trigger example on Contact(after Update){
 
    }
 
    Example :3 Create after insert and after delete trigger opportunity
    trigger opty_Run on Opportunity(after insert ,after delete){
 
    }
 
    Example :4 Create before insert ,before update ,after undelete trigger on Case object
        trigger case_Handler on Case(before insert ,before update ,after undelete){
   
    }
 
 
     9. DML will be performed only when the data is successfully saved to sobject.
        or
    If you want to make any changes on the data which is successfully saved to database then we perfomr DML
    Note : If the data is not saved to database, then we perform write operation
 
    Account acc =new Account();
    acc.Name='Testing'; //Write
    acc.Industry='Energy'; //write
    acc.Rating='Hot';
    if(acc.Rating=='Hot'){
    acc.Ownership='Private';
    acc.Rating='Warm';
    }
    insert acc; // DML operation
    Account a=[select id,type from Account where id=:acc.Id];
    a.type='New Customer';
    update a; // Modified in the database
 
    10. Insert Triggers :
    a. Insert triggers are fired when we try to insert a new record or records into database.
    b. We can insert the record using
    1. Edit pageLayout
    2. Apex class .
    3. VF page
    4. Annonymous window
    5. DataLoader
    6. Import wizard
    7. tools
    8. Webservice
    etc...
 
    c. By Default every trigger is bulk trigger.
 
    d. Before Insert Triggers :
    1. This trigger will be fired before the new records are saved to database.
    2. The list of new records which we are trying to insert into database are defined in Trigger.new
    3. In the Before Insert Trigger  on the data which is available in Trigger.New  we can perform
       below Read,Write
    4. In the Before Insert Trigger  on the data which is available in Trigger.New  we cannot perform
       below Soql,DML
 
    ---------------------------------------------------------------------------
    Trigger Evernt Variable Read Write Soql DML
    ----------------------------------------------------------------------------
    Before Insert Trigger.New Yes Yes No No
 
---------------------------------------------------------------------------------------------------------
    Example :1
    When ever a new Account is Created then set rating as Warm ,ownership as Private ,type as prospect
  and Active as Yes
---------------------------------------------------------------------------------------------------------

        trigger Account_Trigger_1 on Account (before insert) {
            // Trigger.New : This will contain list of new records which we want to insert
            for(Account a: Trigger.New){
                a.Rating='Warm';
                a.Ownership='Private';
                a.Type='Prospect';
                a.Active__c='Yes';
            }
        }
 
   ---------------------------------------------------------------------------------------------------
        Example 2:
        When ever new Account is Created with indsutry as Banking then assign wilson as
        owner of the record
   ----------------------------------------------------------------------------------------------------
        trigger example on Account( before Insert ){
             /* Fetch the Id of the user wilson  */
            User u=[select id from User where alias='wil'];
     
            /* Take one by one record from Trigger.new  */
            for(Account a : Trigger.New){
                if(a.industry=='Banking'){
                    a.ownerId=u.Id;
                }
            }
        }
   
---------------------------------------------------------------------------------------------------
        Example :3
        When ever a new Opportunity is Created  then assign stageName as prospect ,closeDate as
        15 days from today ,amount as 50k leadSource as Web
----------------------------------------------------------------------------------------------------
        trigger example on Opportunity(before insert ){
            for(Opportunity op: Trigger.New){
                op.stageName='Prospect';
                op.closeDate=System.today()+15;
                op.amount=50000;
                op.leadSource='Web';
            }
        }
  11. After Insert Triggers:
    a. These triggers are fired after new record is saved successfully into database.
    b. Trigger.New  : This will contain list of new records which are inserted successfully into sobject.
    c. Trigger.NewMap: This will contain list of new records which are inserted successfully into sobject
    in the form of Map.
   
    Trigger Event Variable Read Write Soql DML
    -------------------------------------------------------------------------------------
    After Insert Trigger.New Yes No Yes Yes
   
    After Insert Trigger.NewMap Yes No Yes Yes
 
   
    ------------------------------------------------------------------------------------------------------
    Example 1 :
        When ever a new Account is Created with rating as Hot then create opportunity for the account
    ------------------------------------------------------------------------------------------------------
    <!--
trigger Account_Trigger_2 on Account (after insert) {
                List<Opportunity> optyList =new List<Opportunity>();
                /* Take one by one new Account which is Created newly */
                for(Account a: Trigger.New){
                    /* Check the rating
                     * if rating is Hot then Create a Opportunity
                     */
                    if(a.rating=='Hot'){
                        Opportunity op=new Opportunity();
                        op.AccountId=a.Id;
                        op.Name=a.Name;
                        op.CloseDate=System.today()+15;
                        op.StageName='Prospecting';
                        op.Type='New Customer';
                        optyList.add(op);
                    }
                }
                insert optyList;
}
    -->
    --------------------------------------------------------------------------------------
    Example 2:
    When ever new Account is Creatd with ownership as private then create wilson as
    AccountTeamMember with Read Access on Account and Account Manager as TeamMemberRole
   
    AccountId , UserId ,AccountAccessLevel,TeamMemberRole
    --------------------------------------------------------------------------------------
    <!--
trigger example on Account(after Insert ){
    List<AccountTeamMember> teams =new List<AccountTeamMember>();
User u =[select id from User where firstName='Wilson'];
for(Account a : Trigger.New){
if(a.ownership=='Private'){
AccountTeamMember atm =new AccountTeamMember();
atm.accountId=a.Id;
atm.UserId=u.Id;
atm.AccountAccessLevel='Read';
atm.TeamMemberRole='Account Manager';
teams.add(atm);
}
}
    insert teams;
    }
-->



12. Update Triggers :
    a. Update triggers are fired when we try to modify the existing data in the object.
    b. There are two types of update triggers
    1. Before Update Triggers
    2. After Update Triggers
    c. Before Update Trigges :
    1. When we are modifying any record  in the object, before the changes on the record
       are saved to the database ,Before Update triggers are fired.
   
    2. Trigger.old :
    1. It is a list of records .
    2. It will contain old version of records on which we have performed Update .
   
    3. Trigger.OldMap
    1. It is a Map of records,with record id as key and record as value.
    2. This will contain old version of thre records on which we are performing update
 
    4. Trigger.New :
    1. It is a list of records .
    2. It will contain new version of records on which we have performed Update .
   
    5. Trigger.NewMap
    1. It is a Map of records,with record id as key and record as value.
    2. This will contain new version of thre records on which we are performing update
 
    d.  Event   Variable Read Write DML SOQL
       -----------------------------------------------------------------------------
    Before Update Trigger.Old Yes No No Yes
 
    Before Update Trigger.OldMap Yes No No Yes
 
    Before Update Trigger.New Yes Yes No No
 
    Before Update Trigger.NewMap Yes Yes No No
 
    ----------------------------------------------------------------------------------------------
    Example :1
    When ever phone number of the account is modified update the corresponding contacts
    otherPhone as Account old Phone number
    mobilPhone as Account new Phone number
    ----------------------------------------------------------------------------------------------
    <!--
trigger example on Account( before Update ){

// Fetch all the accounts with old version of records
Map<Id,Account> oldMap=Trigger.oldMap;

// Fetch all the accounts with new version of records
Map<Id,Account> newMap=Trigger.newMap;
List<Id> accIds=new List<Id>();
// Take one by one account and check weather phone is number is modified or not
Set<Id> keys =oldMap.keySet();
for(Id k : keys){

Account old=oldMap.get(k);
Account acc=newMap.get(k);
if(old.Phone!=acc.Phone){
// if the phone number is modified then add the id of the account to accIds
accIds.add(k);
}
}
// Write query to fetch all the contacts of those acounts whose accountId is in accIds
List<Contact> contacts =[select id ,AccountId,OtherPhone,MobilePhone from Contact where accountId in: accIds];
// Take one by one contact and update the data
for(Contact c: contacts){
Account old=oldMap.get(c.accountId);
Account acc=newMap.get(c.accountId);
c.otherphone=old.Phone;
c.mobilePhone=acc.Phone;
}
update contacts;

}

-->
    -------------------------------------------------------------------------------------------------------------
    Example 2:
    When ever stageName is modifed to closed won create student as OpportunityTeamMember
    ---------------------------------------------------------------------------------------------------------
    <!--
trigger Opty_Trigger_1 on Opportunity (after Update) {
                User u =[select id from User where alias='slive'];
                List<OpportunityTeamMember> teams =new List<OpportunityTeamMember>();
                /* Get the Old Version of Recorsd in the form of Map */
                Map<Id,Opportunity> oldMap=Trigger.OldMap;
                /* Get the new Version of records in the form of Map */
                Map<Id,Opportunity> newMap=Trigger.NewMap;
                /* Get the keys from the Map */
                Set<Id> keys =oldMap.keySet();
                for(Id k: keys){
                    /* Based on the recordId fetch old Version of record and newVersion of the record */
                    Opportunity old=oldMap.get(k);
                    Opportunity newOpt=newMap.get(k);
                    /* If old value of stageName is not closed won
                     * new Version of stageName is closed won then  create  a team Member
                     */
                    if(old.stageName!='Closed Won' && newOpt.StageName=='Closed Won'){
                        OpportunityTeamMember otm =new OpportunityTeamMember();
                        otm.OpportunityId=k;
                        otm.UserId=u.Id;
                        otm.OpportunityAccessLevel='Read';
                        otm.TeamMemberRole='Account Manager';
                        teams.add(otm);
                    }
                }
                insert teams;
            }



   


========================================================================

    Example 1: Whenever a new lead is created Set LeadSource as Web, status as Not Contacted
       rating as warm.

    trigger example on Lead( before insert)
          {
    for(Lead l:Trigger.new)
                      {
    l.leadsource='Web';
    l.status='Not Contacted';
    l.rating='Warm';
    }
    }
 
    Example 2: Whenever a new Opportunity is created, set stage name as Prospecting, close date as 15 days
       from today, type as new Customer
 
    trigger example on Opportunity (before insert){
    for(Opportunity op : Trigger.New){
    op.stageName='Prospecting';
    op.closeDate=System.today()+15;
    op.type='New Customer';
    }
    }
 
    Example 3: Whenever a new Case is created set the Subject as Hardware, priority as Normal
    trigger example on Case(before insert){
    for(Case c: Trigger.new){
    c.Subject='hardware';
    c.Priority='Noramal';
    }
    }
    Example 4: When ever a new Account is created with industry as Banking create wilson as owner
       in the industry is other Banking then set Satish as owner.
    trigger demo on Account (before insert){
    User u1= [select id from User where firstName='Satish'];
    User u2 =[select id from user where firstname='Wilson'];
    for(Account a: Trigger.New){
    if(a.industry=='Banking'){
    a.ownerId=u2.id;
    }else{
    a.ownerId=u1.id;
    }
    }
    }
     
    Example 5: Whenever a new lead is created with a rating as Hot and lead source as web then
    assign HRTeam as owner else assing sales team as owner
   
 
    trigger example on Lead(before insert){
    Group g1 =[select id from Group where type='Queue' and name='Sales Team'];
    Group g2=[select id from Group where type='Queue' and name='HRTeam'];
    for(Lead l: Trigger.new){
    if(l.rating=='Hot' and leadsource=='Web'){
    l.ownerId=g1.id;
    }else{
    l.ownerId=g2.Id;
    }
    }
    }
 
    Example 6: On Lead object, we have Lookup fields to User with field Name: Manager
      When ever a lead is created send email to leads Manager
       Subject : Test Email
       Body  : Dear Customer ,
       Thanks for showing intrest
   <!--
    trigger example on Lead (before insert){
    List<Id> userIds =new List<Id>();
Map<Id,String> userMail =new Map<Id,Email>();
// fetch all the managerId's of the new leads which we are inserting
    for(Lead l: Trigger.new){
    userIds.add(l.Manager__c);
      }
// User Id is the key and his email address is the value in the map
List<User> users =[select Id ,email from the user where id in:UserIds];
for(User u : users){
usermail.put(u.id,u.email);
}
for(Lead l : Trigger.New)
                             {
String email=userMail.get(l.Manager__c);
String[] toadd=new String[]{email};
Messaging.SingleEmailMessage msg =new Messaging.SingleEmailMessage();
msg.setToAddresses(toadd);
}
    }
   

1 comment: