23 March 2015

Roll-up Summary Trigger (for Lookup Fields)

Many times over the course of my career I've bumped into this requirement, where a roll-up summary field is required on an object which does not have a master-detail relationship with another child object, rather a standard lookup field is used. As we know, the standard roll-up summary field only works with master-detail relationships, so in order to enable roll-ups for lookups we need to write some APEX.

Now this is not some break-through innovation or something that people are having trouble with, rather, it's a helper method that I've written to make my life easier by making it dynamic and have it here on my blog, because every single time this requirement comes up, I dig through my old projects to find the similar code that I've written some time ago, or sometimes I even write it from scratch. Let this serve you as a quick reference or a template which you can extend and add your extra bits and pieces like filter criteria etc.


It's basically just one method that you can put in your trigger handler class, and it takes the following 6 arguments:
  1. parentSObjectType (String) - API name of the parent object
  2. parentSumField (String) - API name of the field on the parent object to which you want to store your roll-up value
  3. childSObjectType (String) - API name of the child object
  4. childRollupField (String) -API name of the field on the child object that the roll-up runs against
  5. childLookupField (String) - API name of the lookup field on the child object to the Parent object
  6. aggregateOperation (Enum) - The aggregate operation for the roll-up (AVG, COUNT, MIN, MAX or SUM)
The method will return a list of parent sObject records ready to be updated, which allows for some extra logic before you actually perform a DML on the collection. Below you can see a simple example that rolls up a currency field:

  • Parent Object - Invoice__c
  • Parent Sum Field - Credit_Amount__c
  • Child Object - Credit_Match__c
  • Child Rollup Field - Amount__c
  • Lookup Field to Invoice - Invoice_Lookup__c

Note: Be aware of the SOQL governor limits which apply to the SOQL query above. Please ensure that your query does not touch more than 50,000 records (current limit) and consider adding a WHERE clause to reduce the amount of records processed in the query. Keir Bowden has provided a detailed answer on this governor limit.

2 comments:

  1. Boris,

    This is great but my trigger doesn't seem to be recalculating after deletion of the child record.
    Any ideas?

    Thanks heaps

    ReplyDelete
  2. Does it work in the other cases (insert/update)?

    ReplyDelete