My trigger scenario:
Once an account will update then that Account will update with the total amount from All Opportunities on Account level. Account field name would be Total Opportunity Amount.
Create a custom field called Total Opportunity Amount on Account object.
Trigger object: Account Trigger event : before update
Note: No DML statements is required for before update.
My implementation:
trigger accTrigger on Account(before update) { switch on Trigger.OperationType { when BEFORE_UPDATE { accHandler.updateTotalOppAmt(Trigger.new); } } } public class accHandler { public static void updateTotalOppAmt(List<Account> lstAcc) { Set<Id> accIds = new Set<Id>(); for(Account ac : lstAcc) { accIds.add(ac.Id); } List<AggregateResults> agResult = [Select Id, Sum(Amount) totalAmt, AccountId from Opportunity where AccountId in :accIds group by Id, AccountId]; Map<Id, Decimal> mapTotalOppAmt = new Map<Id, Decimal>(); for(AggregateResults ag : agResult) { Id accountId = (Id)ag.get('AccountId'); Decimal oppAmt = (Decimal)ag.get('totalAmt'); mapTotalOppAmt.put(accountId, oppAmt); } for(Account ac : lstAcc) { if(mapTotalOppAmt.containsKey(ac.Id)); { ac.Total_Opp_Amount__c = mapTotalOppAmt.get(ac.Id); } } } } Here, two objects are involved: Account and Opportunity. Could you please explain why we need to use "before update" instead of "after update" in my trigger scenario? Any clarification would be greatly appreciated.