Tuesday, 20 November 2018

How to stop recursive trigger in salesforce



What is a Recursive Trigger :

A recursive trigger is one that performs an action, such as an update or insert, which invokes itself owing to,  say something like an update it performs.

How to avoid Recursive Trigger:

To avoid recursive triggers you can create a class with a static Boolean variable with default value true. In the trigger, before executing your code keep a check that the variable is true or not. Once you check make the variable false.

Example:

Apex Code:
public Class checkRecursive{
    private static boolean run = true;
    public static boolean runOnce(){
    if(run){
     run=false;
     return true;
    }else{
        return run;
 }
    }
}

 Trigger Code:

trigger updateTrigger on anyObject(after update) {
    if(checkRecursive.runOnce())
    {
    //write your code here            
    }
}


Example2: Scenario: There is an after update trigger on account object. In the trigger, there is a date field we are checking the date is changed or not if it is changed we are doing some process.The trigger is executed five times in the transaction. ​
Apex Code:
public class ContactTriggerHandler
{
     public static Boolean isFirstTime = true;
}
Trigger Code:
trigger ContactTriggers on Contact (after update)
{
    Set<String> accIdSet = new Set<String>(); 
    if(ContactTriggerHandler.isFirstTime)
    {
        ContactTriggerHandler.isFirstTime = false;
         for(Contact conObj : Trigger.New)
  {
            if(conObj.name != 'Test') 
     {
                accIdSet.add(conObj.accountId);
            }
         }
   // any code here
    }
}

=====================================================================================

Apex Class Code:
public class checkRecursive {
     public static Set<Id> SetOfIDs = new Set<Id>();
}
Trigger Code:
trigger TestTrigger on Account (before insert) {
    if (Trigger.isAfter && Trigger.isInsert) {
        List<Account> accList = new List<Account>();
      for (Account test: Trigger.new) {
          If(!checkRecursive.SetOfIDs.contains(test.Id)){
              test.Name = 'helloworld'; 
              accList.add(test);
            checkRecursive.SetOfIDs.add(test.Id);
          }
      }
      insert  accList;
    }
}

No comments:

Post a Comment