When working with Dynamics CRM, there are instances where you may need to calculate rollup field dynamically when a related record is deleted. This is crucial when the deletion of a child record should trigger an update on the parent record (such as recalculating a total, sum, or count). Achieving this requires leveraging Plugins in combination with Pre-Delete and Post-Delete stages.
Let’s walk through the process of setting up a plugin to automatically calculate a rollup field when a related child record is deleted.
Step 1: Pre-Delete and Post-Delete Execution
To begin, we need to implement two Execute functions in our plugin: one for the Pre-Delete stage and one for the Post-Delete stage.
Pre-Delete:
- In the Pre-Delete stage, we retrieve the GUID of the parent record. This is accomplished using the PreImage feature, which captures the state of the entity before the delete operation is executed.
- We pass this GUID to the Post-Delete stage through a shared variable, ensuring the plugin can access the parent record information during the subsequent stage.
Post-Delete:
- In the Post-Delete stage, we use the GUID of the parent record (which was passed from the Pre-Delete function) to perform the necessary calculation for the rollup field.
Example Code Snippet
Step 2: Registering the Plugin
Now, let’s look at the registration of our plugin, which consists of two key actions:
Pre-Delete Registration:
- Register the plugin on the Pre-Operation stage of the Delete message for the child entity.
- We also need to register a PreImage to capture the state of the parent record before deletion. In the PreImage, we’ll pass only the parent GUID, as this is the critical piece of information we need for the rollup calculation in the Post-Delete step.
Post-Delete Registration:
- Register the plugin on the Post-Operation stage of the Delete message for the child entity. This ensures that after the child record is deleted, the rollup calculation is performed
Conclusion
In summary, using a plugin to dynamically calculate rollup fields in Dynamics CRM when related child records are deleted offers a powerful way to ensure your parent records always reflect the most up-to-date data. By leveraging the Pre-Delete and Post-Delete stages, along with shared variables, you can efficiently track changes and trigger necessary recalculations without needing manual interventions or scheduled workflows.




Comments
Post a Comment