Rollup Summary to get the Count of Opportunity Records on Account #inSalesforce

Rollup Summary to get the Count of Opportunity Records on Account #inSalesforce


Handler Class:

public class RollupOpportunityHandler {
    public static void updateOpportunityCount(List<Opportunity> opportunities) {
        Set<Id> accountIds = new Set<Id>();
        for (Opportunity opp : opportunities) {
            if (opp.AccountId != null) {
                accountIds.add(opp.AccountId);
            }
        }
        List<Account> accountsToUpdate = new List<Account>();
        for (AggregateResult result : [
            SELECT AccountId, COUNT(Id) oppCount
            FROM Opportunity
            WHERE AccountId IN :accountIds
            GROUP BY AccountId
        ]) {
            Id accountId = (Id)result.get('AccountId');
            Integer oppCount = (Integer)result.get('oppCount');
            Account acc = new Account(Id = accountId, Opportunity_Count__c = oppCount);
            accountsToUpdate.add(acc);
        }
        if (!accountsToUpdate.isEmpty()) {
            update accountsToUpdate;
        }
    }
}


Apex Trigger:

trigger RollupOpportunityTrigger on Opportunity (after insert, after update, after delete) {
    List<Opportunity> opportunities = new List<Opportunity>();
    if (Trigger.isInsert || Trigger.isUpdate) {
        opportunities.addAll(Trigger.new);
    } else if (Trigger.isDelete) {
        opportunities.addAll(Trigger.old);
    }
    if (!opportunities.isEmpty()) {
        RollupOpportunityHandler.updateOpportunityCount(opportunities);
    }
}

Comments