Showing posts with label How To Avoid Recursion in Apex Trigger. Show all posts
Showing posts with label How To Avoid Recursion in Apex Trigger. Show all posts

Monday, April 17, 2023

How To Avoid Recursion in Apex Trigger

Recursion is the process of executing the same Trigger multiple times to update the record again and again due to automation. There may be chances we might hit the Salesforce Governor Limit due to Recursive Trigger.

To avoid these kind of situation we can use public class static variable.


In RecursiveTriggerHandler class, we have a static variable which is set to true by default.

public class RecursiveTriggerHandler{
     public static Boolean recursiveCheck = true;
}

In following trigger, we are checking if static variable is true only then trigger runs. Also we are setting static variable to false when trigger runs for first time. So if trigger will try to run second time in same request then it will not run.

trigger SampleTrigger on Contact (after update){
  Set<String> accIdSet = new Set<String>();
  if(RecursiveTriggerHandler.recursiveCheck){
      RecursiveTriggerHandler.recursiveCheck = false;
      for(Contact conObj : Trigger.New){
          if(conObj.name != 'SFDC'){
              accIdSet.add(conObj.accountId);
          }
      }
  }
}


1. Trigger runs, recursiveCheck variable value will be checked.
2. In the first run, variable will be true.
3. Then recursiveCheck variable value will be set to false.
4. Next time same IF condition will fail and recursion is stopped.

Mostly Viewed