You need to sign in to do that
Don't have an account?
LiorG
I'd like to share Apex code I wrote for Using a Trigger to make a rollup field
Check it out here: http://www.liorgot.com/1/post/2013/03/using-a-trigger-as-rollup-field-for-lookup-relationship.html
trigger TotalChargedCalculator on OpportunityLineItem (after insert, after update, after delete) { Set<Id> customObjIds = new Set<Id>(); // Grab Ids of all the Custom Object records affected by operation for (OpportunityLineItem oli : trigger.new == null ? trigger.old : trigger.new) { if (trigger.isDelete) { if (oli.Custom_Object__c != null) customObjIds.add(oli.Custom_Object__c); } else { if (oli.Custom_Object__c != null) customObjIds.add(oli.Custom_Object__c); if (trigger.isUpdate) { if (trigger.oldMap.get(oli.Id).Custom_Object__c != null && oli.Custom_Object__c == null) { customObjIds.add(trigger.oldMap.get(oli.Id).Custom_Object__c); } } } } if (customObjIds.size() > 0) { Map<Id, Custom_Object__c> customObjsToUpdateMap = new Map<Id, Custom_Object__c>([ Select Id, Total_Charged__c From Custom_Object__c Where Id IN :customObjIds]); // Query for an Aggregate Result List finds the sum of all the Opp line Item's total price per Custom Object AggregateResult[] customObjIdTotalChargedAgg = [ Select SUM(TotalPrice) totalCharged, Custom_Object__c From OpportunityLineItem Where Custom_Object__c = :customObjIds Group By Custom_Object__c]; // Create Map of custom object Id and sum of total price of related Opp Line Items Map<Id, Decimal> customObjIdToTotalChargedMap = new Map<Id, Decimal>(); for (AggregateResult agg : customObjIdTotalChargedAgg) customObjIdToTotalChargedMap.put((Id)agg.get('Custom_Object__c'), (Decimal)agg.get('totalCharged')); // Get new total charge value from customObjIdToTotalChargedMap, if it doesn't exist in the map, it means TotalPrice Sum is 0 for (Id cId : customObjsToUpdateMap.keySet()) customObjsToUpdateMap.get(cId).Total_Charged__c = customObjIdToTotalChargedMap.get(cId) != null ? customObjIdToTotalChargedMap.get(cId) : 0; update customObjsToUpdateMap.values(); } }
Great work Lior !!!!!
Thanks a lot for sharing with us :D