function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
CBBsfdcCBBsfdc 

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) 
Hi,

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)
        setOpportunityIds.add(o.id);
    
    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')));
                lstAmtToUpdate.add(acc);
            }
        }
    }
    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