Use table extensions to extend the OnModify trigger rather than OnBefore/AfterModify subscriptions where possible. If you must use subscribers then be aware of some of the unexpected situation they are called in.
One of those situations is when a related table has been renamed. The Modify events are thrown in secondary tables e.g. if an Item record is renamed than all of its Item Ledger Entry records will have OnBeforeModifyEvent and OnAfterModifyEvent fired.
If you need to hang some custom logic off the back of a record modification (in a standard table) then I think you’ve got three main options:
- Create a table extension and add an OnModify trigger
- Add a subscription to the OnBeforeModifyEvent or OnAfterModifyEvent for the table in question
- Subscribe to the events in the Global Triggers codeunit to set the table mask and listen for modifications on the table you are interested in
In general I think that is the order of preference i.e. if you can use a table extension, do.
Why Use Events Then?
This isn’t really the point of this post – but why might you use events then. In short, when you can’t use a table extension. That will usually be for one of two reasons:
- The modify trigger isn’t called i.e. the base app calls Modify(false)
- You don’t know which tables you want to work with at design time – your app has got some setup to determine which tables to support maybe in some integration scenario or like Change Log Setup
Considerations For Modify Subscriptions
OK, you’ve decided to use event subscriptions to the OnBefore/AfterModify events. Now to the point of the post. There are some things you need to be aware of:
- They are called for temporary records – most of our subscribers start with a Rec.IsTemporary() check
- They are called whether or not the modify trigger has been called – the RunTrigger parameter indicates whether Modify(true) or Modify(false) was called
- You need to explicitly call Rec.Modify if you make any changes to Rec with an OnAfterModifyEvent subscription otherwise your changes will not be persisted
What’s in a Rename?
You probably knew all of that anyway, What I didn’t know until today is that the events are fired if a parent table is renamed. For example, if you rename an Item record then these events will be fired for each Item Ledger Entry record. Which makes sense and might be exactly what you want.
We hadn’t thought of that and it was the cause of a bug in our app. Shame on us.