want to create a trigger on Account where i can make sum of all amounts of opportunity related list of the current account and all its child Accounts.whenever the record is created or updated

Class code:

public with sharing class Amountopportunities 
    public void onBeforeInsert(List < Account > newacc)
    {   List<Account>acclist =new List<Account>();
        Double x=0;
        for(Account acc:[Select Id,ParentId,(Select Amount From Opportunities),(Select Id,Total_Amount__c From ChildAccounts) From Account where id IN : newacc ])

              for (Opportunity objOpp : acc.Opportunities)
                       if(objOpp.Amount != null)
                         x += objOpp.Amount;
              for(Account acc2:acc.ChildAccounts)



  • 3
    have you tried any thing? – C0DEPirate May 6 '16 at 9:24
  • 1
    Account is the Parent and Opportunity is the Child. Why don't you use Rollup Summary Field for your requirement...? Why Trigger...? Any reasons? – Subhash May 6 '16 at 9:25
  • @kurunve pointed out why we cant use roll up. We need to sum opportunities of child accounts – C0DEPirate May 6 '16 at 9:33
  • i want to use trigger because i want to perform the action on updation of any field of the account – rahulseth May 7 '16 at 4:39
  • from above question there is one requirement also tha the amount field of parent account should also get updated automatically – rahulseth May 7 '16 at 4:40

Edited Answer:

You can use below approach.
1. To calculate the sum of amount from child opportunities create a Roll-Up Summary field on Account Let's say Opportunity Amount. (No code required)
Doing so you will get sum of opportunity on each account.
2. Create another field on Account which will store the sum of Amount from Opportunity Amount of child Accounts Lets say this field as Child Accounts Sum.
3. Create a formula field to add Opportunity Amount and Child Accounts Sum let's say this field is Grand Total
4. You can write trigger for calculating sum of Child Accounts Sum or you can use app exchange solution https://appexchange.salesforce.com/listingDetail?listingId=a0N30000009i3UpEAI

  • are you sure that that would work for all child account opportunities? – kurunve May 6 '16 at 9:29
  • i am not sure but i need the solution of that – rahulseth May 11 '16 at 5:06
  • Downvoted... :( Have you even tried the above suggestion ? – C0DEPirate May 11 '16 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.