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
Dipa87Dipa87 

Help Bulkifying Trigger

Hi All,

 

I have the following trigger to get a sum of all the opportunity amount under an account(as we have advanced multi currency enabled so trying to create a custom roll up summary field).

 

How to bulkify this trigger?Plz help.

 

trigger tgr_change_in_amount on Opportunity (after insert,after update,before delete) {

 for (Opportunity opp: Trigger.new) {
                    if(opp.accountid != null){
                                                       
                            Integer amt;
                            AggregateResult[] groupedResults  = [SELECT SUM(Amount)aver FROM Opportunity where accountid =:opp.accountid];
                            for (AggregateResult ar : groupedResults) { 
                               amt =  Integer.valueOf(ar.get('aver'));
                            }
                           
                            List<Account>lstAccount = new List<Account>();
                            lstAccount = [select Total_Amt_of_Open_Opportunities__c from Account where id=:opp.accountid];
                            lstAccount[0].Total_Amt_of_Open_Opportunities__c = amt;
                           
                            update lstAccount;
                    }
            }

}

prady-cmprady-cm

Something like this should work.. Pls check for syntactical errors, just wrote this on the fly

trigger tgr_change_in_amount on Opportunity (after insert,after update,before delete) {
	Set<id> accIds = new Set<Id>();
	Map<Id,Integer> accAmount = new Map<Id,Integer>();
	List<Account> lstAccount = new List<Account>();
	for (Opportunity opp: Trigger.new) 
	{
		if(opp.accountid != null)
		{
			accIds.add(opp.accountid);
		}
	}
	
	AggregateResult[] groupedResults  = [SELECT id,SUM(Amount)aver FROM Opportunity where accountid In :accIds];
	for (AggregateResult ar : groupedResults) 
	{ 
		accAmount.put(ar.Id,Integer.valueOf(ar.get('aver')));
	}
	
	for(Account a :[select id, Total_Amt_of_Open_Opportunities__c from Account where id IN :accIds])
	{
		a.Total_Amt_of_Open_Opportunities__c = accAmount.get(a.Id);
		lstAccount.add(a);
	}
	
	update lstAccount;

}