Development questions
Write a trigger to calculate the sum of Amount of all Closed Won Opportunities and store it on the parent Account.
Use triggers on Opportunity (after insert, update, delete, undelete), gather parent Account Ids (old and new on update), aggregate Closed Won amounts, and update the Accounts.
apex
trigger OppRollup on Opportunity (after insert, after update, after delete, after undelete) {
Set<Id> accIds = new Set<Id>();
for (Opportunity o : (Trigger.isDelete ? Trigger.old : Trigger.new)) {
if (o.AccountId != null) accIds.add(o.AccountId);
if (Trigger.isUpdate && Trigger.oldMap.get(o.Id).AccountId != null)
accIds.add(Trigger.oldMap.get(o.Id).AccountId);
}
Map<Id, Decimal> sums = new Map<Id, Decimal>();
for (AggregateResult ar : [SELECT AccountId a, SUM(Amount) s FROM Opportunity
WHERE AccountId IN :accIds AND StageName = 'Closed Won' GROUP BY AccountId]) {
sums.put((Id) ar.get('a'), (Decimal) ar.get('s'));
}
List<Account> accs = new List<Account>();
for (Id id : accIds) accs.add(new Account(Id = id, Total_Won_Amount__c = sums.containsKey(id) ? sums.get(id) : 0));
update accs;
}
apex-triggertriggercodingscenariorollup
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?