Pages

Tuesday, December 22, 2015

A Tale of Two Triggers

The following is a cautionary tale about the importance of having only one* trigger per object type. It is based on actual events. Only the names, apex code, and events have been changed.

Imagine you have a trigger something like the one that appears below, along with its associated support Apex class.

Don't worry too much about reading all the code. Just know that the trigger fires after insert or update of an Opportunity record to do some processing. The first order of business is to ensure that the trigger hasn't already run in the current context due to other triggers that may be present in the org. We want to prevent multiple calls to the trigger in one transaction and the potential for trigger recursion. This is achieved via a static set of Opportunity Ids. Once we've processed a given Opportunity Id and put it in the set there is no need to revisit it again in the current transaction.

Now the fun begins. Users report that the desired functionality from the after insert trigger code isn't always occurring in production. The first step is to acquire the associated debug log to see what is going on.

Here is an extract from the DEBUG logging messages for the OppTrg_MyProductIntegration class when the assertion fails:

Going carefully through the log, there is another rogue after insert trigger in there that is resulting in an update on the record that was just inserted. This subsequent update causes our trigger of interest to execute first in an update context, before returning to execute for the original insert. The Set of processed Id's is tripping us up here. When the trigger first fires for update the ID isn't in the Set, so the fields are checked for a changed value. Being an update on another field the check doesn't pass, and the additional processing is skipped.

Which brings us back to the moral of the story, the only way to get predictable trigger ordering is to have one trigger per object type that passes off to other classes in a defined order. This is sometimes easier said than done. Multiple managed packages can all introduce their own set of triggers.

It terms of fixing the example triggers above, we can assume that the action should always occur in a trigger context. Basically bypass the Set check unless it is an update operation.