trigger countingof on lead (after insert,after update,after delete){
   set<id>  conId = new set<id>();
   map<id,list<lead>> countle= new map<id,list<lead>>();
   if(trigger.isafter && trigger.isinsert || trigger.isUpdate ){
    for(lead c: trigger.new){
  if(trigger.isafter && trigger.isDelete){
    for(lead c:trigger.old){
 list<lead> leadlist= [select id ,owner_type__c  , no_of_lead__c  from lead where owner_type__c In :conId];
  for(lead a :leadlist){
      countle.put(a.owner_type__c, leadlist);
 list<lead> lst=new list<lead>();
 list<lead> countlist = [select id, no_of_lead__c,owner_type__c  from lead where owner_type__c in :conId];
    for(lead a : countlist){ 
       list<lead> lstt=countle.get(a.owner_type__c);
       a.no_of_lead__c= lstt.size();
       system.debug('@@@a' +a);  
       update lst;

Error:Apex trigger countingof caused an unexpected exception, contact your administrator: countingof: execution of AfterUpdate caused by: System.DmlException: Update failed.


There are multiple issues with your trigger

  1. I see that the way you form the "countle" map is not correct .

  2. I see update statement inside FOR loop

  3. Very important ,you are facing recursion .

You are trying to update leads which in turn again will call your trigger and this will lead to recursion and salesforce reports as unexpected error .

There is a free tutorial on Trailhead that will guide you how to write effective triggers .

If you are trying to update leads in same context ,you can stop recursion via static boolean .

Look at the help article to understand what is recursion and how you can prevent it

  • if i remove after update and isupdate so its work properlly. i understood and fix for loop which is running in updatelist. – deepak Apr 7 '16 at 5:43

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.