+ Start a Discussion

Write a Trigger to roll-up Opportunity Amount on a custom field on Account Object

Best Answer chosen by CBBsfdc
Khan AnasKhan Anas (Salesforce Developers) 

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
trigger RollUpOppAmt on Opportunity (after insert) {
    Set<Id> setOpportunityIds=new Set<Id>();
    for(Opportunity o:Trigger.new)
    List<Account> ListOfAmt = [select id, Amount__c from Account];
    List<Account> lstAmtToUpdate=new List<Account>();
    for(AggregateResult result:[SELECT AccountId, SUM(Amount) FROM Opportunity 
                                WHERE Id IN :setOpportunityIds GROUP BY AccountId]) {
        for(Account acc : ListOfAmt) {
            if(result.get('AccountId') == acc.Id) {
                if(acc.Amount__c == null) {
                    acc.Amount__c = 0;
                acc.Amount__c = acc.Amount__c + Decimal.ValueOf(String.ValueOf(result.get('expr0')));
    if(lstAmtToUpdate.size()>0) {
    	UPDATE lstAmtToUpdate;

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas