========================================================================
trigger ContactTrigger on Contact (After insert,After update,After Delete,After Undelete) {
set<id> accIds = new Set<Id>();
ContactTriggerHelper helper = new ContactTriggerHelper();
if(Trigger.IsAfter && (Trigger.isinsert || Trigger.isUpdate || Trigger.isUndelete )){
for(Contact con : Trigger.New){
if(con.AccountId != null){
accIds.add(con.AccountId);
}
}
}
if(Trigger.IsAfter && (Trigger.isUpdate || Trigger.isdelete )){
for(Contact con : Trigger.Old){
if(con.AccountId != null){
accIds.add(con.AccountId);
}
}
}
if(accIds != null) {
helper.updateAccoutTotals(accIds);
}
}
=====================================================================
public class ContactTriggerHelper { public void updateAccoutTotals(set<id> acIds){ List<AggregateResult> agrls = [SELECT Accountid accid,Count(Id) cnt,
SUM(Payment__c) sm FROM COntact WHERE Accountid
in :acIds Group By Accountid]; list<Account> lstAccs = new List<Account>(); for(AggregateResult agr : agrls){ Account acc = new Account(); acc.Id = String.valueOf(agr.get('accid')); acc.Total_Count__c = Double.valueOf(agr.get('cnt')); acc.Total_Payemnts__c = Double.valueOf(agr.get('sm')); lstAccs.add(acc); } update lstAccs; } }