Prevent an Apex Trigger from executing twice

I came across an issue recently whereby the following conditions were met:

  1. An after update trigger was updating based on some Trigger.old != (a specific value had changed)
  2. A workflow ran
  3. The same after update trigger executed, because Trigger.old was still !=

The goal, of course, was to have the trigger to run only once. A side effect of the trigger was occurring twice.

The fix to having this occur lies within a static variable in the handler class. I use Mike Leach’s Simple Trigger Template whenever possible, with the following added to the Handler class:

public static boolean firstRun = true;

and in the OnAfterUpdate method:

if (firstRun) {
	firstRun = false;
else {
	System.debug('Already ran!');

This worked. Solution from Jitendra Zaa

This entry was tagged , , . Bookmark the permalink.

9 Responses to Prevent an Apex Trigger from executing twice

  1. Mike Leach says:

    Great addition to the template. Thanks for sharing!

  2. Pingback: Apex Triggers the Definitive Guide ‹ MacsCloud

  3. Jagan says:

    This hack is now suggested in the Apex Developer Guide in the section using static variables and methods. Page 112. (summer 12 release).

  4. Gareth says:

    This also blocks re-entry processing for Bulk triggers for records 201+

    Consider using set or map static variable to keep track of records already processed

    • Ray Dehler says:

      Gareth — ok, interesting. Worthy of noting that this falls apart for bulk api.

      • Anton Zeef says:

        for the record, the apex dev guide states in the page referenced by Jagan:

        For Apex saved using API version 20.0 or earlier, if an API call causes a trigger to fire, the batch of 200 records to process is further split into batches of 100 records. For Apex saved using API version 21.0 and later, no further splits of API batches occur. Note that static variable values are reset between batches, but governor limits are not. Do not use static variables to track state information between batches.

        So, there is no bulk api problem if you’re using API after 20.0.

        • F says:

          That’s not the case for Collections inserted/updated in Apex code.
          A collection of 201+ records will have the trigger firing just for the first batch. I strongly advice against using this pattern as I seen it failing way too many times.

  5. Jeff Douglas says:

    Ray, thanks for the great code. I was having the same issue and this was a nice sanity check.


Comments are closed.