Jun 4, 2013

Calculate total from related entity values

This is a very common scenario. For example Quote entity contains fields to have total of all the relevant quote product values. Yet, we don’t need to bother about it since CRM is taking care of those totals. Suppose we need to do such calculation in our custom scenario it will not be handled by CRM.

Just like Quote and Quote product (or Opportunity and Opportunity product), suppose we got entity that has related records as child records or line items. Each child record could have a value for surcharge and primary entity should have the total surcharge. How you accomplish this? In other terms, when child values get changed total should get changed.


Now we will consider the events that child values could change. They are Create, Update and Delete. Obviously we need to write plug-ins for those events to adjust the total. Below would be our algorithm;

Total (Surcharge) = Sum of All Line Item (Surcharge)

Now consider different events;

Post Create – Execute above algorithm

Post Update – Execute above algorithm

What about the delete?

This is the tricky part. Since there is nothing called post-delete, obviously we need to run this in pre-delete. Still we don’t get expected value by executing the same algorithm in pre delete. Why? This uses pre values. In this case total will not be affected by the calculation. Total will not get deducted the value of deleted child record. How we solve this?

You will only have to update the surcharge value of the deleting record to zero in pre delete plug-in. When you do this, post-update plug-in will execute and total will be set except for the record which will be deleted soon. So this is the correct out come!

No comments:

Post a Comment