Last Updated on January 21, 2022

Recursive Trigger In Apex

In this blog, we will learn how we can avoid the recursive triggers in apex code. In Salesforce it is recommended that there should be a single trigger for a single object. The reason behind this is you can not be sure about the sequence of occurrence for your triggers. Salesforce facilitates multiple things to automate your business process such as Workflow, Process Builder, and lastly APEX classes.

Also Read: How To Call Flows From Apex In Salesforce

What Is Recursion?

Consider a scenario where you have written an update code on a contact object whenever its parent account gets updated. To achieve this you are using the update trigger of account (Suppose trigger A) and updating your contacts. Suppose another developer is working on the same org and he wants to update the account object whenever a contact gets updated. Also, he is using a contact trigger(Suppose trigger B) to update the parent account. Now, what if admin update an Account object called 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.

hire salesforce developers

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
    }
}

No matter multiple people or salesforce consultants working in your org or not it is always a best practice to keep your code secure from all known and possible issues. So I recommend using this. I hope this will help you. Keep Exploring.

Learn More: How To Fetch Records By Lightning Data Service In Salesforce

Avatar photo
Author

With a decade of experience in eCommerce technologies and CRM solutions, Virendra has been assisting businesses across the globe to harness the capabilities of information technology by developing, maintaining, and improving clients’ IT infrastructure and applications. A leader in his own rights his teammates see him as an avid researcher and a tech evangelist. To know how the team Virendra can assist your business to adopt modern technologies to simplify business processes and enhance productivity. Let’s Talk.