Preventing Recursive Triggers in Salesforce Apex Code

Apex Recursive Trigger


In this blog post, we’ll explore methods to circumvent recursive triggers in Apex code. Salesforce advises having a solitary trigger for a specific object, primarily due to the unpredictability of trigger occurrence sequences. Salesforce provides various tools for automating business processes, including Workflow, Process Builder, and ultimately, APEX classes.

What Constitutes Recursion?

Imagine a situation where you’ve implemented code to update a contact object whenever its parent account undergoes an update. In this scenario, you utilize the update trigger of the account (Let’s call it trigger A) to perform the updates on your contacts. Concurrently, another developer in the same organization aims to update the account object whenever a contact is updated. This developer employs a contact trigger (Let’s call it trigger B) to handle the updates on the parent account. Now, consider the scenario where an admin updates an Account object named John Doe.

Account object called John doe

As we can see this situation tends to call these triggers in a loop. This situation is called recursion. It can be due to workflow or process builder as well. So recursion occurs when the same piece of code runs again and again, in a non-ending loop or sometimes in an unwanted output.

How to Avoid

In order to avoid this situation, we will go to a static variable. As we know static variables can be initialized only once. We will use this feature to avoid recursion in our code.

Let’s do this with an example.

public class RecursiveTriggerHandler{
     public static Boolean isExecuted = false;
}

trigger RecursiveTrigger on Account (before update){
 
    // Check your variable first. If it calls second time will set as true and your if the condition fails
     
    if(!testTriggerHandler.isExecuted){
        // Now since its first time set it to true 
        testTriggerHandler.isFirstTime = true;
         
        // Do your coding part here
    }
}

Whether multiple individuals or Salesforce consultants are involved in your organization or not, it is consistently advisable to secure your code against known and potential issues. Therefore, I suggest incorporating this practice. I trust it proves beneficial for you. Keep exploring!