function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Donald HurseyDonald Hursey 

Trigger to rollup (count) number of child records, grouped by picklist value and add to parent

I wanted to find out if there is a way to rollup the number of records based on the "type" picklist and then add those totals to the parent record related through a look up field. 


I have the code below which works fine to update the field "Opens" on the parent. (just included the "isInsert" part to keep the example simple)

Is there a way to do this so I wouldn't need a  seperate query for eachrecord type? These records usually come in batches from a 3rd party app.

I'm not sure how connect a query such as [select count(Id) count, activiyType__c from childObject__c group by activiyType__c] with the parent id in a map that can be used in the dml. 

any help is greatly appreciated.
 

trigger pickListCount on wbsendit__Campaign_Activity__c (after insert, after update,after delete) {

    if(trigger.isInsert){

            // list to collect query for all history records
            
            List<CMRules__Email_Tracking_Summary__c> summaryList = new List<CMRules__Email_Tracking_Summary__c>();

            for(AggregateResult agr : [SELECT count(id) ct,CMRules__Email_Tracking_Summary__c c FROM  wbsendit__Campaign_Activity__c where wbsendit__Activity__c = 'Opened' GROUP BY CMRules__Email_Tracking_Summary__c LIMIT 50000]){
                if((ID)agr.get('c')!=null){
                    CMRules__Email_Tracking_Summary__c sum = new CMRules__Email_Tracking_Summary__c(id = (ID)agr.get('c'),CMRules__Opened__c = (Integer)agr.get('ct') );
                    summaryList.add(sum);
                    }
                }
                update summaryList;
            }
}
 



 

Best Answer chosen by Donald Hursey
SecondID PatelSecondID Patel
Instead of using AggregateResult, I would like to suggest you create some temporary variables and use if-else condition based on the wbsendit__Activity__c then increase the count by 1 every time it goes inside the if or else condition...and in the last update the corresponding fields on the Parent lookup...It will be easy to handle...

Hope this makes sense...Please let me know if you want the code on the same.