In this post, We will try to understand what is recursion and how to solve recursion in Salesforce. Recursion is caused when the same code is executed multiple times which results in an Infinite loop execution. This, in turn, causes the Governor limits to be hit and the code/execution will result in an error.
Scenario: We want to update an Email field on Lead Object through the trigger(After update event) and if there is already an existing process builder/workflow with Same Email Field update then this results in Recursion.
How to Avoid Recursion: In order to avoid recursion, we need to Create a Static Variable with a Boolean flag and check the value in the trigger code.
public class recursionUtility{
public static boolean isInitialrun =true;
}
In Lead trigger, we will try to use the utility code and skip the execution after the first run.
trigger LeadTrigger on Lead (after update){
List<String>emailIdList =new List<String>();
//Verify if the trigger already ran once
if(recursionUtility.isInitialrun){
//After the run set the isInitialrun flag to false as we do not want it to be executed multiple times.
recursionUtility.isInitialrun =false;
for(Lead ld : Trigger.New){
if(ld.Email !=”){
emailIdList.add(ld.Email);
}
}
Update emailIdList;
}
}