Create a trigger that calculates and updates a custom field on the Account object named TotalOpportunityValue whenever an Opportunity related to that Account is created, updated, or deleted. The field should represent the sum of the Amount field of all related Opportunities.
Hello @Swati Patle
You can take reference from below code.
Trigger TotalOpportunityAmount on Opportunity (after insert,after update,after delete,after undelete ) {
List<Account> oppListToIterate = Trigger.isDelete ? Trigger.old : Trigger.New;
List<Account> accountListToUpdate = new List<Account>();
set<Id> accountIds=new set<Id>();
for(Opportunity opp:oppListToIterate){
if((Trigger.isInsert || Trigger.isDelete) && opp.ExpectedRevenue != null )
accountIds.add(opp.accountID);
else if(Trigger.isUpdate && (opp.ExpectedRevenue != Trigger.oldMap.get(opp.Id).ExpectedRevenue)){
accountIds.add(opp.accountId);
}
else if(Trigger.isUpdate && (opp.AccountId != Trigger.oldMap.get(opp.Id).AccountId)){
accountIds.add(opp.accountId);
accountIds.add(Trigger.oldMap.get(opp.Id).accountId);
}
}
for(AggregateResult ar : [SELECT AccountId AcctId,SUM(ExpectedRevenue) totalRevenue FROM Opportunity WHERE AccountId in :accountIds group by AccountId]){
accountListToUpdate.add(
new Account(
Id = (Id) ar.get('AcctId'),
TotalRevenue__c = (Integer) ar.get('totalRevenue');
)
);
}
if(!accountListToUpdate.isEmpty())
UPDATE accountListToUpdate;
}
In case you find any other issue please mention.
If you find your Solution then mark this as the best answer.