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);

Written by 

3x Salesforce MVP | Platform Champion | 18x Salesforce Certified | MuleSoft Certified | 8x Trailhead Ranger | TechForce Services | Sydney | Australia

Leave a Reply

Your email address will not be published.