In this post lets walk through an example on how we can use delegates in the new AX to develop customizations.
Quick summary of delegates: X++ delegates expose the publisher - subscriber pattern where a delegate defines a clear contract in a publisher class. It is a great way of encapsulating a piece of code. Delegates were introduced in AX 2012 couple of years back. With the new AX release delegates are the recommended way for customizing standard AX classes.
Let’s jump into action and customise standard AX sales order confirmation process. To keep it simple we will the change value of a field in confirmation journal table. The idea here is how to develop delegates and call them.
Confirmation journal header data is stored in CustConfirmJour table and it is initialised in the below class method during the sales confirmation posting process. Let’s modify it using delegates.
First
we create a new delegate method in this class. This serves the purpose of defining a contract between the delegate instance and the delegate
handler. There is no business logic inside the delegate method. Also notice
that the delegates have return type as Void. In order to access the result
value we have to pass EventHandlerResult
object as a parameter.
Now we modify the actual method, declare the Event handler result object and call
the delegate with the parameters in the method which we need to customise . The only customization in this method is 2 lines of code as highlighted below:
Now we create the
event handler method and this is where MS has done really nice stuff in moving
the AX development environment to Visual Studio. Right click on the
delegate method and copy the handler method definition.
Create a new class
which will be used to subscribe to the delegate. So we create a new class, let
call is salesConfirmJournalExt and paste the copied
clipboard text
The delegate handler
definition is automatically added with the below information:
Now we can add our
custom code in this method. I just changed the purchase order field
value and added some Infolog. Note that I am actually not returning anything in
this method and not using the eventHandlerResult object really.
So we are done. The see it wokring let's
build the solution and confirm a sales order.
The confirmation
journal has the custom text appended to it in the field we used in our new class method.
Microsoft strongly
recommends to use Delegates for customization due to all the good reasons of
having minimum code changes in standard product. So try to use delegates to have a
cleaner and manageable solutions.
Feel free to share your feedback. Below are some good online references on Delegates:
https://blogs.msdn.microsoft.com/x/2011/08/02/how-to-use-x-delegates-in-dynamics-ax-2012/
https://en.wikipedia.org/wiki/Observer_pattern