Enquiry Now

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

Get in Touch

Avatar photo
Author

With over a decade of experience in eCommerce development services and CRM solutions, Mr. Virendra has helped businesses worldwide leverage technology to build, optimize, and transform their IT infrastructure and applications. An avid researcher, Mr. Virendra is recognized by his peers as a tech evangelist with a strong passion for emerging technologies and their potential to solve real-world business challenges. Discover how Team Virendra can help your business embrace modern technology, simplify operations, and drive greater productivity. Connect.

whatsapp