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
LiorGLiorG 

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();
 
			 	}
 	 }

 

Gupta.VishalGupta.Vishal

Great work Lior !!!!! 

 

Thanks a lot for sharing with us :D