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
Soumya ChoudhurySoumya Choudhury 

before trigger not updating the field while using Map

Hi,

I have the below trigger, where I intend to update the Account record if the linked opportunity has been staged to "Qualification".

trigger mapAccount on Opportunity (before insert,before update) {
    
    List<Opportunity> ol=[select id,Account.rating from Opportunity where id in: Trigger.new and StageName='Qualification'];
    Map<ID,Opportunity> mp=new Map<ID,Opportunity>();
    System.debug('----------');
    
    for(Opportunity o:ol){
        o.Account.rating='Cold';
        mp.put(o.id, o);
        System.debug('Rate--'+o.Account.rating);
    }
    System.debug(mp.values());
}


But, Using this, the account Rating is not getting updated. Please explain the reason.

Thanks in Advance !
Suraj TripathiSuraj Tripathi
Hi Soumya, 

I made some Changes in your code now it is working fine.
 
List<Opportunity> ol=[select id,Account.rating from Opportunity where id in: Trigger.new and StageName='Qualification'];
    Map<ID,Opportunity> mp=new Map<ID,Opportunity>();
    System.debug('----------');
    list<account> AccList= new list<account>();
    
    for(Opportunity o:ol){
    Account acc = new account();
        acc.Id=o.Accountid;
        acc.rating='Cold';
        AccList.add(acc);
        mp.put(o.id, o);
        System.debug('Rate--'+o.Account.rating);
    }
    update AccList;
    System.debug(mp.values());

    }

Hope it helps you.

Regards 
Suraj
TruptiTrupti
Hello Soumya,

Though Before Trigger do not need any DML for updation of record on which you are writing a trigger,in your requirement you are trying to update related object value hence we need to use DML for updation.

See below code which works for me:

trigger mapAccount on Opportunity (before insert,before update) {
    List<Account> accountList = new List<Account>();
    List<Opportunity> lstOpp= new Map<Id,Opportunity>([SELECT id,Account.rating 
                                                         FROM Opportunity 
                                                         WHERE id IN: Trigger.new 
                                                         AND StageName='Qualification']);
    
    if(lstOpp != NULL && lstOpp.size() > 0){
        for(Opportunity o:lstOpp){
            Account accToUpdate = new Account(id = o.AccountId,rating='Cold');
            accountList.add(accToUpdate);
        }
    }
    if(accountList != NULL && accountList.size() > 0)
    update accountList;
}