Recursive triggers in Salesforce

Recursive triggers in Salesforce

     You want to write a trigger that creates a new record as part of its processing logic; however, that record may then cause another trigger to fire, which in turn causes another to fire, and so on. You don’t know how to stop that recursion.

     Use a static variable in an Apex class to avoid an infinite loop. Static variables are local to the context of a Web request (or test method during a call to runTests()), so all triggers that fire as a result of a user’s action have access to it.

Example:
     Suppose there is a scenario where in one trigger perform update operation, which results in invocation of second trigger and the update operation in second trigger acts as triggering criteria for trigger one.

Solution:

Class:

public class Utility
{
    public static boolean isFutureUpdate;
}

Trigger:

trigger updateSomething on Account (after insert, after update)
{

    /*  This trigger performs its logic when the call is not from @future */
    if(Utility.isFutureUpdate != true)
    {

        Set<Id> idsToProcess = new Se<Id>();

        for(Account acct : trigger.new)
        {
            if(acct.NumberOfEmployees > 500)
            {
                idsToProcess.add(acct.Id);
            }
        }

        /* Sending Ids to @future method for processing */
        futureMethods.processLargeAccounts(idsToProcess);

    }
}

Class:

public class FutureMethods
{

    @future
    public static void processLargeAccounts(Set<Id> acctIDs)
    {

        List<Account> acctsToUpdate = new List<Account>();

        /* isFutureUpdate is set to true to avoid recursion */
        Utility.isFutureUpdate = true;
       
        update acctsToUpdate;
    }
}

Leave a Reply