Thursday, March 1, 2018

How to make a DML operation in a trigger After insert/update (Recursion Trigger)

Many times I’ve faced requirements to write a field in a trigger after the record is inserted or update. So, naturally I’ve tried something like this:
But there the record is read only and if you try to change a field value this exception will be fired:
execution of AfterInsert caused by: System.FinalException: Record is read-only
The workaround is quite simple. The object contained by the global trigger.new is read-only, but you can create a new object referring the same ID and change the value that you need.
In addition you have to avoid the recursion since you are changing the record the trigger will be fired again. To avoid that you have to use a static flag which says that the trigger has been already executed during the current executing context.
So, the final code should be like this:

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.