+ Start a Discussion

Trigger for a rollup on a formula field

I need to create a roll up summary on a field that is a formula. However, I have never written a trigger and was hoping someone would be able to walk me through the steps of doing so. The field is on the opportunity products and I need the rollup to be the sum of that field on the opportunity.


Thanks you for any help or suggestions provided!


Please be aware that formulas do not "change" the database, and therefore do not cause trigger actions to fire. This means, notably, that cross-object formulas and formulas which depend on time will not correctly update the parent records until the parent or children records are edited. With that statement out of the way, here's how you do what you're trying to do:


trigger updatekids on kid__c (after insert, after update, after delete, after undelete) {
   set<id> parents = new set<id>();
     for(kid__c k:trigger.new)
     for(kid__c k:trigger.old)
   update [select id from parent__c where id in :parents];
trigger updateparents on parent__c (before update) {
  for(aggregateresult ar:[select parentid__c parentid, sum(formula__c) formula from kid__c where parentid__c in :trigger.new group by parentid__c]) {
    trigger.newmap.get((id)ar.get('parentid')).formula_sum__c = (decimal)ar.get('formula');

This simple mechanism works for all master-detail and lookup (non-master-detail) relationships, even if the child record changes parents.


You need to change parentid__c, formula__c, parent__c, and kid__c to reflect actual database names.


Thank you so much! Just a few more questions for clarification. Again, I have never attempted this before, so I apologize for silly questions...


Since I am building this to sum a custom formula field on the opportunity products, the kid_c would be that field, the parent_c would be the field where I want the summed total to be, correct? How do I determine the parentid_c and formula_c?


With the first box, I create a trigger on the opportunity products and the second is on the opportunity, correct?


Thank you again for the help!