Skip to main content
Hi

I am updating account field rating='Hot' whenever Opportunity stageName='Closed won'.

I would like to understand 2 things

a) account field rating is not updated when I edit any opportunity record and set the StageName='Closed Won'

b) How to use Map function in order to avoid loop.correct me if I am wrong.

 

public 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);

}

}

}

Thanks

pooja
4 个回答
  1. 2016年4月14日 05:34
    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 Won

    Its 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.

    public 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();

    }

    }

    }

    Please let me know if that helps you.

    Best Regards,

    BALAJI

     
0/9000