Tuesday, January 21, 2014

How to restrict any Trigger to fire only once

How to restrict any Trigger to fire only once

 Triggers can fire twice, once before workflows and once after workflows, this is documented at

http://www.salesforce.com/us/developer/docs/apexcode/ Content/ apex_triggers_order_of_execution.htm:

“The before and after triggers fire one more time only if something needs to be updated. If the fields have already been set to a value, the triggers are not fired again.”

Workaround:

Add a static boolean variable to a class, and check its value within the affected triggers.
public class HelperClass {
   public static boolean firstRun = true;
}
trigger affectedTrigger on Account (before delete, after delete, after undelete) {
    if(Trigger.isBefore){
        if(Trigger.isDelete){
            if(HelperClass.firstRun){
                Trigger.old[0].addError('Before Account Delete Error');
                HelperClass.firstRun=false;
            }
        }
    }
}

No comments:

Post a Comment