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
Naveen Ashok SirivellaNaveen Ashok Sirivella 

Creating rollup summary values for lookup by using triggers

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
Best Answer chosen by Naveen Ashok Sirivella
Rahul.MishraRahul.Mishra
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 

All Answers

Raj VakatiRaj Vakati
use this tool it will generate the code for you 
https://appexchange.salesforce.com/listingDetail?listingId=a0N3000000B45gWEAR
Rahul.MishraRahul.Mishra
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 
This was selected as the best answer
Steven NsubugaSteven Nsubuga
Trigger CountOpportunitiesPerAccount on Opportunity (after insert, after update, after delete) {
    
    Set<Id> accountIds = new Set<Id>();
    List<Account> accountsToUpdate = new List<Account>();
    
    if (trigger.isInsert || trigger.isUpdate) {
        for (Opportunity opp : Trigger.new) {
            if(opp.StageName != 'Closed Won' && opp.StageName != 'Closed Lost' && opp.AccountId != null) {
                accountIds.add(opp.AccountId);
            }
        }   
    }
    if (Trigger.isDelete){  
        for (Opportunity opp : Trigger.old) {
            if(opp.StageName != 'Closed Won' && opp.StageName != 'Closed Lost' && opp.AccountId != null) {
                accountIds.add(opp.AccountId);  
            }
        }
    }
    
    // get a map of the Account with the number of Opportunities
    Map<id, Account> accountMap = new Map<id, Account>([select id, Open_opportunities_count__c from Account where id IN :accountIds]);
    for (id accountId : accountMap.keySet()) {
        accountMap.get(accountId).Open_Opps__c = 0;
    }
    
    List<AggregateResult> ars = [SELECT AccountId, count(Id) FROM Opportunity WHERE AccountId IN :accountIds AND StageName NOT IN ('Closed Won','Closed Lost') group by AccountId];
    for (AggregateResult ar : ars) {
        accountMap.get(String.valueOf(ar.get('AccountId'))).Open_opportunities_count__c = Integer.valueOf(ar.get('expr0'));
    }
    update accountMap.values();
}