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.

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.

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
    }
}

Permanent link to this article: https://www.sfdcpoint.com/salesforce/avoid-recursive-trigger-salesforce/

3 comments

    • sandy on July 19, 2020 at 2:42 am
    • Reply

    Hi Ankush,

    Can u Please elabarate in this Post the use of static variable ,Why it is used
    and without using static how it will behave?

    • SFDC on January 7, 2022 at 11:44 pm
    • Reply

    Static Variables can be called via a class reference

    • NoviceDev on July 13, 2023 at 8:09 am
    • Reply

    Thanks to this post I was able to solve an issue (i.e my trigger going into ininite loop due to recursion) that I’ve been stuck on for hours. I’m very grateful. 🙌🙌🙌

Leave a Reply

Your email address will not be published.