Skip to main content
Hi All,

I want to create rollup summary fields on Account object.

Scenario : calculate how many open opportunities (except closed won,closed lost) and populate on account record.

please find the below code

trigger CalculatingOpenOpportunity on Opportunity (After insert) 

{

     if(Trigger.isInsert && Trigger.isAfter)

      {

          Set<id> accountids = new Set<id>();

          List<Account> acclist = new List<Account>();

          for(Opportunity opp : trigger.new)

          {

             if(opp.StageName != 'Closed Won' && opp.StageName != 'Closed Lost')

             {

                 accountids.add(opp.id);

                 system.debug('values in the accountids:========================================>'+accountids);

             }

          }

          

          // get a map of the accounts 

         Map<id,Account> accountMap = new Map<id,Account>([select id,Open_opportunities_count__c from Account where id IN :accountids]);

         System.debug('values in the accountMap :=============================================>'+accountMap);

        //Quering related opportunities and accounts.

        for(Account acc:[select id,name,Open_opportunities_count__c,(select id,name,StageName from opportunities) from Account where ID IN :accountids])

        {

             accountMap.get(acc.Id).Open_opportunities_count__c = acc.Opportunities.size();

             System.debug('values in the accountMap.get(acc.Id).Open_opportunities_count__c:================================>'+accountMap.get(acc.Id).Open_opportunities_count__c);

             //Adding count and opportunities to list

             acclist.add(accountMap.get(acc.Id));

        }

        

        if(acclist.size() > 0)

         {

           System.debug('Size of the acclist :==============================>'+acclist.size());

           database.update(acclist);

         }

      }

}

Please help on above scenario's
3 件の回答
  1. 2018年7月2日 17:12
    Hi Naveen,

    Below is the code for you, just copy paste:

     

    trigger addTeam on Opportunity (After insert) {

    Set<Id> setOfAccountIds = new Set<Id>();

    List<Account> lstAccountToUpdate = new List<Account>();

    for(Opportunity opp : trigger.new) {

    if(opp.StageName != 'Closed Won' && opp.StageName != 'Closed Lost' && opp.AccountId != null) {

    setOfAccountIds.add(opp.AccountId);

    }

    }

    for(Account acc : [Select Id, Open_opportunities_count__c, (Select Id, StageName From Opportunities Where

    StageName != 'Closed Won' AND StageName != 'Closed Lost'),

    Name From Account Where Id IN:setOfAccountIds]) {

    lstAccountToUpdate.add(new Account(Id = acc.Id, Open_opportunities_count__c = acc.Opportunities.size()));

    }

    if(!lstAccountToUpdate.isEmpty())

    update lstAccountToUpdate;

    }

    Mark solved if it works as expected for your requirment 
0/9000