How to avoid recursive trigger execution in Salesforce

Apex Trigger – Apex Trigger is a piece of code that executes Before and After a record is Inserted, Updated, Deleted in a Database.

What is Recursion in Trigger?

Recursion is when same code is executing again and again & it exceeds the “Governor Limit”.

AccountTriggerHandler Helper Class:-

public Class AccountTriggerHandler{
    //Trigger execution check variable
    public static Boolean runOnce = true;
    
    //On before update
    public void onBeforeUpdate(map<Id, Account> mapNewAccount, map<Id, Account> mapOldAccount){
        //Write your logic here
        System.debug('Is Before Update');
    }
    
    //On after update
    public void onAfterUpdate(map<Id, Account> mapNewAccount, map<Id, Account> mapOldAccount){
        Update [SELECT Id, Name FROM Account WHERE Id IN: mapNewAccount.keyset()];
        AccountTriggerHelper.runOnce = true;
        System.debug('Is After Update');
    }
}
AccountTrigger in Account Object:-
trigger AccountTrigger on Account(before Update, after Update) {
    
    AccountTriggerHandler handler = newAccountTriggerHandler();
    
    if(Trigger.isBefore && Trigger.isUpdate && handler.runOnce){
        handler.onBeforeUpdate(Trigger.newMap, Trigger.OldMap);    
    }
    
    if(Trigger.isAfter && Trigger.isUpdate && handler.runOnce){
        handler.runOnce = false;
        handler.onAfterUpdate(Trigger.newMap, Trigger.OldMap);
    }
}
Reference:

(94)

Written by 

I am Sakthivel Madesh, a certified Salesforce Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 13x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply