Eventing OnAfterModify: Watch out when checking against xRec

Yesterday, I needed to put some code after modification of a record. So I decided to use the event for this.
My code only needed to be updated if some field was updated.

After coding my functionality, I went on testing, but found out my code didn’t execute correctly…
Well, you might remember the source of the “problem” from older versions: https://msdn.microsoft.com/en-us/library/dd338629.aspx

In short, if you put code in the OnModify Trigger, the xRec variable would contain the same as the Rec variable, if you changed the record through code. There was an easy solution to this problem.

Right before checking the xRec variable you could do something like this:

and all was well.

However, when using eventing, the process works a bit different. (see also this post from Vjeko)
Basically, the code gets executed in the trigger, the records is modified on SQL (but not yet committed, so an error will still trigger a rollback)

Next, the event subscribers are triggered. And the same issue with xRec happens here. The xRec contains the same as the Rec variable if changed through code.

So, the logical first step is to try the get method again.
However, this still returns an already changed record. If you read through the post of Vjeko, you might remember you even need to MODIFY the record explicitly.
This means the triggers will write the information to SQL after the trigger is done executing, but before the events are raised.

So, If you need to check the changed data (although only if the change was done through code), the only way to check the old values is by subscribing to the onBeforeModify event.

Leave a Reply