Development questions

When an OpportunityLineItem is inserted or deleted, update a custom field on the parent Account (Total_Products_Purchased__c).

DevelopmentHardAccentureInfosysPwC

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