Development questions

Write a trigger to calculate the sum of Amount of all Closed Won Opportunities and store it on the parent Account.

DevelopmentMediumAccentureEYLTIMindtree

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