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
rathi007rathi007 

Apex trigger Count_Opp caused an unexpected exception,Count_Opp: execution of AfterUpdate caused by

trigger Count_Opp on Account (After insert, after update) {
list<opportunity> opplist=new list<opportunity>();
list<Account> acclist=new list<account>();
list<Account> acclist1=new list<account>();
set<id> id ;
integer won=0;
integer lost=0;
integer total=0;
for(Account a:Trigger.new)
{
id.add(a.id);
}
opplist=[select StageName,name from opportunity where Accountid=:id];
for(opportunity opp:opplist)
{
if(opp.StageName=='Closed Won'&&opp.name!=null)
{
won++;
total++;
}else if(opp.StageName=='Closed Lost'&&opp.name!=null)
{
lost++;
total++;
}
else{
total++;
}
}
acclist=[select No_of_won_opp__c,No_of_lost_opp__c,Total_opp__c from Account where id=:id];
for(Account acc:acclist)
{
acc.No_of_won_opp__c=won;
acc.No_of_lost_opp__c=lost;
acc.Total_opp__c=total;
acclist1.add(acc);
}
update acclist1;
}

sandeep@Salesforcesandeep@Salesforce

Please share exact error message.

AshlekhAshlekh

 

Hi,

 

You are try to update a list of Account (name of list is acclist1).

 

This acclist1 and Trigger.new having same account records.

 

we always get a problem  whenever we try to update the value of object record on which objcet we write a trigger on after update or after insert  event  because that records are locked we can not update the value of that records on after event on trigger.

 

for this you have changed the event after to before.

 

Thanks

Ashlekh

 

If this post helps you and mark it as a solution and don't forget to give me kudos.