You need to sign in to do that
Don't have an account?
Lukesh Karmore
Apex trigger to update account rating when the opportunity stage equals closed won
my code is -
trigger UpdateAccRatingToHot_WhenOppStageIsClosedWon on Opportunity ( before insert) {
list<account> accounts = new list<account>();
for(account acc : [select name, rating from account]){
for(opportunity opp : trigger.new){
if(opp.stagename == 'closed won'){
acc.Rating = 'Hot';
accounts.add(acc);
}
}
}update accounts;
}
It gives me error of too many SOQL queries Why??
trigger UpdateAccRatingToHot_WhenOppStageIsClosedWon on Opportunity ( before insert) {
list<account> accounts = new list<account>();
for(account acc : [select name, rating from account]){
for(opportunity opp : trigger.new){
if(opp.stagename == 'closed won'){
acc.Rating = 'Hot';
accounts.add(acc);
}
}
}update accounts;
}
It gives me error of too many SOQL queries Why??
Greetings!
You are getting this error because you are trying to query the records inside the loop and the query is running more than 100 times.
Reference:https://help.salesforce.com/articleView?id=000331875&type=1&mode=1
I don't think you need to query the records here.You can simply use the list to update the rating field.
Please mark it as best answer if it helps you to fix the issue.
Thank you!
Regards,
Shirisha Pathuri
trigger UpdateAccRatingToHot_WhenOppStageIsClosedWon on Opportunity ( before insert) {
set<id> AccountIdset = new set<id>();
for(opportunity opp : trigger.new){
AccountIdset.add(opp.AccountId);
}
list<account> accountList = new list<account>([select name, rating from account where id in: AccountIdset ] );
for(account acc : accountList){
for(opportunity opp : trigger.new){
if(opp.stagename == 'closed won' && acc.id == opp.AccountId){
acc.Rating = 'Hot';
accounts.add(acc);
}
}
}update accounts;
}
Please mark your best Answer