
Thankspoojapublic class updateaccountrating
{
public void updaterating(List<Opportunity> oppor)
{
// 1. Get opportunity accountID and store in a list.
Set<ID> opporAccountID = new Set<ID>();
for(Opportunity o:oppor)
{
opporAccountID.add(o.AccountID);
}
List<Account> aFinal=new List<Account>();
List<Account> acc=[select ID,rating from account where ID IN :opporAccountID];
for(Opportunity o:oppor)
{
for(Account a:acc)
{
if (o.StageName == 'Closed Won')
a.rating='Hot';
aFinal.add(a);
}
}
if (aFinal.size() > 0 && aFinal != NULL)
Database.Insert(aFinal,false);
}
}
trigger trg_updateaccountrating on Opportunity (before Insert,before Update)
{
if (trigger.IsBefore)
{
if (trigger.IsUpdate)
{
updateaccountrating a = new updateaccountrating();
a.updaterating(Trigger.New);
}
}
}
Hi Pooja,The two things you want to understand,a) account field rating is not updated when I edit any opportunity record and set the StageName='Closed WonIts because you used Database.Insert(aFinal,false); in the class. Change it to Database.Update (aFinal,false); It will work definitely.b) How to use Map function in order to avoid loop.correct me if I am wrong. Please fing below modified code using Map.
Please let me know if that helps you.Best Regards,BALAJIpublic class updateaccountrating
{
public void updaterating(List<Opportunity> oppor)
{
Map<Id,Account> accountMap = new Map<Id,Account>();
for(Opportunity o : oppor){
if(o.StageName == 'Closed Won'){
accountMap.put(o.Id, new Account(Id=o.AccountId, rating='Hot'));
}
}
//Update all the appropriate accounts in a bulkified manner here.
if(accountMap.size() > 0)
{
update accountMap.values();
}
}
}