This trigger calculates the total Opportunity Amount for all related Opportunities and updates the Account’s Annual Revenue field whenever an Opportunity is created, updated, or deleted.
Explore more examples via this YouTube playlist.
Solution:
//Call this method for insert, update, delete and undelete event public static void populateAmountOnAccount(List<Opportunity>
oppList,Map<Id,,Opportunity> oldMap){ Set<Id> accIds = new Set<Id>();
for(Opportunity opp : oppList){ if(oldMap != null){
if(opp.AccountId!=null&&opp.Amount!=null&&opp.Amount!=old
Map.get(opp.Id).Amount){
accIds.add(opp.AccountId);
}
}else{ if(opp.AccountId != null && opp.Amount != null){
accIds.add(opp.AccountId);
}
}
}
List accList=[SELECT Id,AnnualRevenue,(SELECT Id, Amount
FROM Opportunities) FROM Account WHERE Id IN: accIds];
if(!accList.isEmpty()){ for(Account acc:accList){
Decimal total=0;
for(Opportunity opp:acc.Opportunities){
total=total+opp.Amount;
}
acc.AnnualRevenue=total;
}
}
if(!accList.isEmpty()){
update accList;
}
}