#NAVdevTips 1: After really means after

With Events we have something which is very good. It is control when our code should be run. Some time ago I got task to update all records in my table based on previous record in the same table. Task wasn’t very complicated but how update records when user tries to delete the record in the middle?
And this is where we can use Events. Let’s look on example below. Our last column is multiple of Next No. from previous row and the same field in current row.

So let’s try now to write simple code in OnDelete trigger

What result do we get? As we can see in below screen 6 * 4 is for sure not 30 and as you can see NAV still counts our record which we want to delete. So to achieve our goal we need to do something else.

So maybe Event will do better? I just put the same code to the Subscriber Event OnAfterDeleteEvent.

The result is totally different. Now NAV does not count the record but still sees it as we have access to it thru Rec variable. Also our very hard calculation is correct.

So as you can see – After really means After. The same you can observe with OnAfterInsert where you need to Modify record if you want to assign some value to it.
Microsoft published (link below) the order of running triggers so we can see that first OnBeforeDelete trigger is run (this one also can be triggered by Events), then OnDelete (trigger in table) and OnDatabaseDelete (which is in Codeunit 1). After those three record is deleted from database. Then our OnAfterDelete trigger is run as last one.

Link which can be very useful: https://docs.microsoft.com/en-us/dynamics-nav/developer/devenv-event-types#trigger-events

Add a Comment

Your email address will not be published. Required fields are marked *