anusha(salesforce developer)

Avoid recursive trigger in salesforce

Avoid recursive trigger in salesforce using static variable

Avoid recursive trigger in salesforce using static variable
Recursion occurs when same code is executed again and again. It can lead to infinite loop and which can result to governor limit sometime. Sometime it can also result in unexpected output.
It is very common to have recursion in trigger which can result to unexpected output or some error. So we should write code in such a way that it does not result to recursion. But sometime we are left with no choice.
For example, we may come across a situation where in a trigger we update a field which in result invoke a workflow. Workflow contains one field update on same object. So trigger will be executed two times. It can lead us to unexpected output.
Another example is our trigger fires on after update and it updates some related object and there is one more trigger on related object which updates child object. So it can result too infinite loop.
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.
1
2
3
public class RecursiveTriggerHandler{
     public static Boolean isFirstTime = 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
trigger SampleTrigger on Contact (after update){
 
    Set<String> accIdSet = new Set<String>();
     
    if(RecursiveTriggerHandler.isFirstTime){
        RecursiveTriggerHandler.isFirstTime = false;
         
        for(Contact conObj : Trigger.New){
            if(conObj.name != 'SFDC'){
                accIdSet.add(conObj.accountId);
            }
        }
         
        // Use accIdSet in some way
    }
}

No comments:

Post a Comment