+ Start a Discussion
Lakshmi SLakshmi S 

Rollup summary trigger : calculate average value (shows dml exception)

Hi Dev's

Q). Calculate Average value using custom rollup summary using trigger.
 Objects : Account (parent) - Opportunity(child) -- I want to calculate average amount from opportunity and display in account object.

Program:

trigger RolllupSummaryOppAmt on Opportunity (After insert, After update,After delete, After undelete) {
    Set<Id> accid = new Set<Id>();
    Decimal avgamt;
    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete){
        for(Opportunity opp : Trigger.New){
            if(opp.AccountId != null){
                accid.add(opp.AccountId);
            }
            
        }
    }
    
    if(Trigger.isUpdate || Trigger.isDelete){
        for(Opportunity op : Trigger.Old){
            if(op.AccountId != null){
                accid.add(op.AccountId);
            }
            
        }
    }
        
    List<Account> aclist = [select id,OppAvgAmount__c,(select id,amount from opportunities) from account where id In :accid];
    List<Account> upacc = new List<Account>();
    if(aclist.size()>0){
        for(Account ac : aclist){
           
            List<AggregateResult> aglist = [select avg(amount)agg from opportunity where accountid = :ac.id];
            for(AggregateResult ag : aglist){
                avgamt = (Decimal)ag.get('agg');
                system.debug('---average---:'+avgamt);
            }
            ac.OppAvgAmount__c = avgamt;
            upacc.add(ac);
        }
        
            update upacc;
       
           }

}



Error : Error:Apex trigger RolllupSummaryOppAmt caused an unexpected exception, contact your administrator: RolllupSummaryOppAmt: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0016F00001tLWYSQA4; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Trig_Demo_Update_Opp: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0066F00000n7Je2QAE; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, RolllupSummaryOppAmt: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0016F00001tLWYSQA4; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 0016F00001tLWYS) is currently in trigger Trig_Demo_Update_Opp, therefore it cannot recursively update itself: [] Trigger.RolllupSummaryOppAmt: line 24, column 1: [] Trigger.Trig_Demo_Update_Opp: line 13, column 1: []: Trigger.RolllupSummaryOppAmt: line 24, column 1


Please give me the solution to this issue;

Regards
Lakshmi
ManojjenaManojjena
HI Lakshmi,

Your trigger is falling under recursion so you need to check recursion .
Trig_Demo_Update_Opp you need to you need to add recursion handler to it .

Try to use this code for roll up summery .
 
trigger RolllupSummaryOppAmt  on Opportunity ( after insert, after update,after delete,after undelete) {
	 Set<Id> accIdSet=new Set<Id>();
	 List<Account> accListToUpdate=new List<Account>();
	 if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete){
		  for(Opportunity opp : Trigger.new){
			 if(opp.AccountId != null){
				accIdSet.add(opp.AccountId);
			 }		
		  }
	 }
	 If(Trigger.isDelete){
	   for(Opportunity opp : Trigger.old){
			if(opp.AccountId != null){
			   accIdSet.add(opp.AccountId); 
			}		
		}
	  }
	 for(AggregateResult res : [SELECT AccountId,sum(Amount)can FROM Opportunity WHERE AccountId IN :accIdSet GROUP BY AccountId]) {
		accListToUpdate.add(new Account(Id=(Id)res.get('AccountId'),OppAvgAmount__c=(Double)res.get('can')));
	}
	try{
		update accListToUpdate;
	 }catch(DmlException de){
		System.debug(de);
	 }
}
Try with below link to add recursion handler in trigger .
https://help.salesforce.com/articleView?id=000133752&type=1


Let me know if it helps !!
Thanks
Manoj
 
Lakshmi SLakshmi S
Thanks manoj.
It works by using recursion handler.