Monday, October 28, 2019

USE OF TRIGGER.ISEXECUTING


 Trigger.isexecuting is used to identify that the current context for the Apex code is a trigger and the apex code is not getting called from any other sources like webservice, visualforce page, etc.

In simple words when we want our apex code to execute only when it is getting called from trigger we make use of trigger.isexecuting.

To understand this with an example we will be going to consider the below scenario.

SCENARIO: We are having the requirement to check if the phone number on the account record is getting updated with a new value and if it is getting updated we want the checkbox field(Phone Number Changed) on account record to be marked as true. Also, we want this piece of code in apex class to be fire only when the apex code is getting called from Trigger.

APEX TRIGGER:

trigger AccountMainTrigger on Account (before update) {
    createContactClass obj=new createContactClass();
    if(trigger.isbefore && trigger.isupdate)
    {
     obj.method1(trigger.new,trigger.old);
    }
}

APEX CLASS:

public class createContactClass {
       public void method1(List<Account> newList,List<Account> oldList){
             system.debug('Is trigger executing'+trigger.isexecuting);
                                            if(trigger.isexecuting){ // Checking If the current context for the apex code is a trigger.
                 for(Account newAcc:newList){
                     for(Account oldAcc:oldList){
                         if(newAcc.id==oldAcc.id){
                             if(newAcc.phone!=oldAcc.phone){
                                 newAcc.Phone_Number_Changed__c=True;
                             }
                         }
                     }
                 }
             }
       }
}

Refer the below images for results before and after the update is done on Phone number field.

Initial state of Account record before update,

trigger.isexecuting in salesforce

State of Account record after phone number update,

USE OF TRIGGER.ISEXECUTING



2 comments: