Monday, 5 October 2015

Avoid repeated execution of Trigger

Many times we came across the situation where because of our Workflow Rules or some other cases our same trigger goes into an Infinite Loop or get executed twice - once before workflows and once after workflows, you can find proof here.

“The before and after triggers fire one more time only if something needs to be updated.”

So Lets see one simple example of How to restrict any Trigger to fire only once i.e. avoid repeated or second execution of Trigger in same context -

Solution : 

You need to add one Static Boolean variable to a your utility/helper class (any apex class), and check its value within affected triggers, where you do think this trigger will get fired more than once.


* "MyUtilityClass" is your helper  / utility apex class  where we will have our static boolean variable - e.g. declared as "runOnceFlag= true"

public class MyUtilityClass {
   public static boolean  runOnceFlag= true;
}


* Sample example Trigger - where you will check for the value of static boolean variable "runOnceFlag"- For first time its value will be equal to TRUE, and we will set its value to FALSE in our trigger to avoid second run.

trigger myTriggerName on Account (before delete, after delete) {
   
 
     if(Trigger.isBefore && Trigger.isDelete){
   
         if(MyUtilityClass.runOnceFlag){
                // **************** Your all business logic code goes here  *********                
                               //** and in the end we will update our static boolean variable
                MyUtilityClass.runOnceFlag=false;           }
    }
}