4.3 Avoid infinite loops

What is infinite loop in Salesforce Trigger

Today, we need to introduce a very important concept in Salesforce Trigger – infinite loop. I will show you what it is and how you should avoid them.

Suppose we have an update trigger on merchandise which updates the relevant transaction records. And we also have an update trigger on transaction which updates some relevant merchandise records. Now we have got the problem of infinite trigger loops.

Suppose we update a merchandise, it updates its relevant transaction due to its trigger. Then the transaction trigger also fires because it also gets updated. Then it updates the relevant merchandise back which again updates the transaction. As you can see, we have fallen into a infinite trigger invocation loop here.

How should we avoid this?

The code

The below code is an example of resolving this infinite loop dilemma. In our TriggerHandlerTransaction class:


public class TriggerHandlerTransaction
{
    private List<String> relatedMerchandiseIdList = new List<String>();
    private Map<Id, Merchandise__c> merMap;
    private static Boolean notRunYet = true;

    public void afterInsert()
    {
        if(!notRunYet) 
        {
            return;
        }
        notRunYet = false;
        initializeData();
        calculateRevenue();
        updateData();
    }
    
    public void resetTriggerRun()
    {
        notRunYet = true;
    }
    //...

A little bit explanation

Almost all the latest trigger handler mechanisms (which we will introduce later) will contain infinite loop avoiding mechanism. The implementation varies a little bit, but the concept is the same thing.

We need to have a static variable to store whether this trigger has been run or not. If it is already run, then we can skip the rest part of the trigger.

Please note, that static variable should be private so it can’t be changed from outside the class.

Also, we need to have a resetTriggerRun() method. So in case we have this kind of code:


update listOfMer1;

//...

update listOfMer2;

We can use resetTriggerRun() method to ensure that for both updates, trigger got run smoothly.

Next Post

4.4 Execution Order

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *