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
RSomaniRSomani 

Child parent rollup count

Hi Expert,

I have a account with oppertunities. now  i want to add GrossTotal custom field in Account and all opertunity Amount will be add in Gross total.

Please suggest.

Regards
Romesh
  


 
Best Answer chosen by RSomani
mukesh guptamukesh gupta
Hi Romesh,

Please use below code
 
trigger GrossAmountRollUp on Opportunity (after insert, after update) {
    List<Account> accList = new List<Account>();
    List<Id> listIds = new List<Id>();
    Decimal grossTotal = 0;
    
    for(Opportunity opp: Trigger.new){
        listIds.add(opp.AccountId);
    }
    
 for(Account a: [select Name,(select id, Amount from opportunities) from Account  where id =:listIds])
    {   
       for(Opportunity o:a.opportunities){
          grossTotal  = grossTotal+o.Amount;
        }
        a.dotsquaremukesh__Gross_Amount__c = grossTotal;
        accList.add(a);
            
    }
    
    update accList;
}


Regards
Mukesh

All Answers

GauravGargGauravGarg
Hi Romesh,

There are two ways to achedive this:
Let me know if you need more insight. 

Thanks,
Gaurav
skype: gaurav62990
mukesh guptamukesh gupta
Hi Romesh,

Please use below code
 
trigger GrossAmountRollUp on Opportunity (after insert, after update) {
    List<Account> accList = new List<Account>();
    List<Id> listIds = new List<Id>();
    Decimal grossTotal = 0;
    
    for(Opportunity opp: Trigger.new){
        listIds.add(opp.AccountId);
    }
    
 for(Account a: [select Name,(select id, Amount from opportunities) from Account  where id =:listIds])
    {   
       for(Opportunity o:a.opportunities){
          grossTotal  = grossTotal+o.Amount;
        }
        a.dotsquaremukesh__Gross_Amount__c = grossTotal;
        accList.add(a);
            
    }
    
    update accList;
}


Regards
Mukesh
This was selected as the best answer