Simple Trigger program to calculate roll up summary

  • create a number field on the account object or you can create this number field at any parent object where you want the roll-up summary calculation.
  • Create a trigger file in the developer console on contact(This trigger you can use at any child object like custom or standard).
  • make it after insert

Source Code:

				
					trigger TotalConPrice on Contact (after insert) {
Set accIDs = new Set();
for(Contact con:Trigger.New){
accIDs.add(con.AccountId);
}
List conList = [Select Id,AccountId,Contact_Price__c From Contact Where AccountId In: accIDs];
Map<Id,Decimal> totalPrice = new Map<Id,Decimal>();
for(Contact con : conList){
if(totalPrice.containsKey(con.AccountId)){
Decimal price = totalPrice.get(con.AccountId)+con.Contact_Price__c;
totalPrice.put(con.AccountId,price);
}
else{
totalPrice.put(con.AccountId,con.Contact_Price__c);
}
}
List accList = new List();
for(Id accId : totalPrice.keySet()){
Account acc = new Account();
acc.Total_Contact_Price__c = totalPrice.get(accId);
acc.Id = accId;
accList.add(acc);
}
update accList;
}
				
			

Leave a Comment