trigger UpdateAccOnchangeOpp on opportunity (after insert, after update){
List<Id> accIds = new List<Id>();
List<Account> accounts = new List<Account>();
for(Opportunity o : trigger.new){
if(o.StageName == 'Closed Won'){
accIds.add(o.accountId);
}
}
for(Account a : [SELECT Id, Checkbox__c FROM Account WHERE Id IN :accIds])
{
a.Checkbox__c=true;
accounts.add(a);
}
if(accounts.size()>0){
Update accounts;
}
}
I trust you are doing very well.
Below is the sample code which I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
I hope it helps you.
Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.
Thanks and Regards,
Khan Anas
Please check this Optimised Code for the your query and Please mark this as best answer if you find it positive.
Thanks
Jolly Birdi
I have already solved it
Thanks,
Digna Parmar
Below Code can fulfill your requirements. Hope this will work for you.
Please mark this as best answer if this solves your problem.
Thank you,
Ajay Dubedi
I want the result using Map
list<Id> SetAccountId = new list<Id>();
list<Account> acclist = new list<Account>();
// Map<id,List<opportunity>> mapAccIdAndOpp = new Map<id,List<opportunity>>();
list<opportunity>oppList = new list<opportunity>();
If(Trigger.isInsert){
For (Opportunity opp:Trigger.new){
SetAccountId.add(opp.AccountId);
}
}
If(Trigger.isUpdate || Trigger.IsDelete){
For (Opportunity opp:Trigger.old){
SetAccountId.add(opp.AccountId);
}
}
list<Account> a = [Select id, Active__c, (SELECT Id, StageName FROM Opportunities) FROM Account WHERE id IN :SetAccountId];
for (Account ac:a){
for(Opportunity op : ac.Opportunities){
if (op.StageName =='Closed Won'){
ac.Active__c = True;
}else{
ac.Active__c = False;
}
if(!acclist.contains(ac)){
acclist.add(ac);
}
}
}
System.debug('result '+acclist);
Update acclist;
}
Worked in my case