Free computer code on screen

Salesforce Maximum Trigger Depth Exceeded Error

The Salesforce Maximum Trigger Depth Exceeded Error primarily arises due to recursion within a trigger. Recursion can manifest from various causes, leading to repeated execution of the same code. This cycle can generate an infinite loop, causing a breach in governor limits and sometimes yielding unexpected outputs.

In the described trigger, there’s a check for the contact’s last name not being equal to ‘SFDC’, followed by the preparation of an account ID set. Let’s assume an account record update is triggered within this process. Suppose there’s another trigger responsible for updating contact records when accounts are modified.

trigger SampleTrigger on Contact (after update){
    Set<String> accIdSet = new Set<String>();   
    for(Contact conObj : Trigger.New){
        if(conObj.LastName != 'SFDC'){
            accIdSet.add(conObj.accountId);
        }
    }
    // Use accIdSet in some way to update account
}

In the provided scenario, encountering recursion will lead to the Maximum Trigger Depth Exceeded Error.

A solution to resolve the Maximum Trigger Depth Exceeded Error in Salesforce involves using a public class static variable. To mitigate this issue, implementing a condition within the trigger to prevent recursive calls is recommended.

Within the RecursiveTriggerHandler class, a static variable is initialized as true by default.

public class RecursiveTriggerHandler{
    public static Boolean isFirstTime = true;
}

In the subsequent trigger, it verifies whether the static variable is true before executing the trigger. Additionally, the trigger sets the static variable to false during its initial execution. Consequently, if the trigger attempts to run a second time within the same request, it won’t proceed.

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 to update account
    }
}