When developing in Microsoft Dynamics 365 Business Central, one of the biggest problems we encounter is that some events don’t carry all the necessary parameters in specific points in the application. An example is calculating a new tax from a purchase document.
To solve this problem, you’ll need to employ the parameter persisting pattern. The parameter persisting pattern is more of a workaround than an actual pattern, but it helps to get the job done.
Let’s explore how this works by using the Codeunit 90 Purch-Post as an example. This codeunit, like almost every single codeunit in Business Central, has been refactored for extensibility with several integration events called before and after a specific action. But, in most cases the parameters are not where you need them.
Say that we’re not in preview mode and need to sum the line amount when the purchase document is posted. To fix this problem, we can use the parameter persisting pattern. Here are the steps you need to follow in order to take advantage of the parameter persisting pattern:
Using the Parameter Persisting Pattern Workaround in Business Central
First, we have to create a new single instance codeunit with the parameters that we need to keep during the lifetime of the event.
Next, we define the events that will clear (or initialize) the variables in the single instance codeunit. In our example, we use the OnBeforePostPurchaseDoc and the OnAfterPostPurchaseDoc codeunits.
In the single instance codeunit, we define those procedures to clear or initialize the variables and to get/set the values for those variables.
In a new codeunit, we subscribe to the defined start and finish events. We then call the clear variables function. The call in the end isn’t exactly necessary, but it’s better to be safe than sorry. As you can see, the PreviewMode variable is being captured at the beginning of the posting event.
Then, the persisted variables can be used throughout the lifecycle of the event, as shown in the next example:
This is how you can effectively use the parameter persisting pattern to improve your extensions.