Thursday, March 10, 2016

Developer: Avoiding Recursive Triggers

Triggers allow a developer to perform actions on an object before or after an DML operation like Insert, Update, Delete. As a best practice, it is recommended that 1 trigger per object be written.

Now, if a trigger has a before/after logic for an operation like update then care must be taken to ensure that the trigger does not execute in a loop. An After Update causing a Before Update to fire which in turn causes another After Update and so on....

How to handle Recursive triggers?

Solution

Essentially, you want the code to execute in one instance and not go on firing in a loop.

Create a seperate trigger handler class as follows:

public class RecursiveTriggerHandler{
     public static Boolean isFirstTime = true;
}

Now, in your before trigger you would have something like which essentially invokes the class and sets the static variable isFirstTime.

trigger xxxx on Account (before insert,after insert, after update) {

 If (Trigger.isBefore){
 if (Trigger.isInsert){
If(RecursiveTriggerHandler.isFirstTime){


.....add your code......

Next in the after code insert the following which ensures that for the first execution flow the variable is set to false when it reaches the after operation and so does not cause the trigger logic to keep executing recursively.

f (Trigger.isAfter){
    If (Trigger.isupdate || Trigger.isinsert ){
      if(RecursiveTriggerHandler.isFirstTime){
        RecursiveTriggerHandler.isFirstTime = false;



No comments:

Post a Comment