[SalesForce] How is the second trigger execution processed by Force.com

Hello StackExchangers,

I'm trying to figure out the order execution of triggers and workflows, and I'm wondering if there's a way to detect from a trigger if it is the first or second time it is executed in the same request.

According to the Force.com documentation (Triggers and Order of Execution)

If the record was updated with workflow field updates, fires before and after triggers one more time (and only one more time), in addition to standard validations. Custom validation rules are not run again.

The reason why is because the first time my trigger is executed (an after trigger on the Opportunity object), I execute a DML request to increment a field in a record of the same type. Then, a Workflow is executed to execute a field update, provoking the re-execution of my after trigger. Since the trigger is executed twice, this field is incremented twice in the same request instead of one.

How can I prevent this behavior? Thanks!

UPDATE

This paragraph in the page I mentioned above is refering to this exact problem:

Trigger.old contains a version of the objects before the specific update that fired the trigger. However, there is an exception. When a record is updated and subsequently triggers a workflow rule field update, Trigger.old in the last update trigger won’t contain the version of the object immediately prior to the workflow update, but the object before the initial update was made. For example, suppose an existing record has a number field with an initial value of 1. A user updates this field to 10, and a workflow rule field update fires and increments it to 11. In the update trigger that fires after the workflow field update, the field value of the object obtained from Trigger.old is the original value of 1, rather than 10, as would typically be the case.

It doesn't any solution to detect if it is the first or second time.

Best Answer

Advanced Apex Programming describes how to build a central trigger dispatcher that is designed to alleviate concerns like this. Essentially it boils down to a few things:

  1. Using a static variable to check if you have already begun processing
  2. Having different entry points for new processing vs. re-entry
  3. Taking advantage of the shared context in triggers that launch each other, allowing you to make good use of the static variable in point 1.

You can get the sample code from the website here.

Related Topic