Development questions
When an OpportunityLineItem is inserted or deleted, update a custom field on the parent Account (Total_Products_Purchased__c).
OpportunityLineItem has no AccountId, so query the parent Opportunities to find Accounts, then aggregate line items per Account.
apex
trigger OLITrigger on OpportunityLineItem (after insert, after delete) {
Set<Id> oppIds = new Set<Id>();
for (OpportunityLineItem li : (Trigger.isDelete ? Trigger.old : Trigger.new)) oppIds.add(li.OpportunityId);
Set<Id> accIds = new Set<Id>();
for (Opportunity o : [SELECT AccountId FROM Opportunity WHERE Id IN :oppIds]) if (o.AccountId != null) accIds.add(o.AccountId);
Map<Id, Decimal> totals = new Map<Id, Decimal>();
for (AggregateResult ar : [SELECT Opportunity.AccountId a, SUM(Quantity) q FROM OpportunityLineItem
WHERE Opportunity.AccountId IN :accIds GROUP BY Opportunity.AccountId]) {
totals.put((Id) ar.get('a'), (Decimal) ar.get('q'));
}
List<Account> accs = new List<Account>();
for (Id id : accIds) accs.add(new Account(Id = id, Total_Products_Purchased__c = totals.containsKey(id) ? totals.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?