The Maximum Trigger Depth Exceeded Error in Salesforce primarily arises from trigger recursion. Recursion may happen due to various causes, where the same code is repetitively executed. This situation can generate an infinite loop, potentially reaching governor limits and occasionally yielding unexpected outcomes.
Consider the scenario where the trigger checks if the contact’s last name isn’t ‘SFDC,’ subsequently preparing a set of account IDs. Assume there’s another trigger that updates contact records when accounts are updated.
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 scenario outlined above, encountering recursion would lead to the Maximum Trigger Depth Exceeded Error.
A resolution to address the Maximum Trigger Depth Exceeded Error in Salesforce
To prevent such scenarios, employing a public class static variable proves effective. By setting a condition within the trigger, recursion can be avoided.
Within the RecursiveTriggerHandler class, there exists a static variable initialized to true by default.
public class RecursiveTriggerHandler{ public static Boolean isFirstTime = true; }
Within this trigger, we validate the execution only if the static variable is set to true. Additionally, upon the trigger’s initial execution, the static variable is set to false. Subsequently, if the trigger attempts to execute a second time within the same request, it will be prevented from doing so.
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 } }