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 

trigger to update related records

Hi,
I need to have a trigger to update 'Rating' of an Account to 'Cold', if it's related opportunity is staged to 'Qualification'.
We should use MAP here.

I have tried the below code. But, it is not updating the record of account

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

Could someone help me.
Bhanu joshi 10Bhanu joshi 10
Hello
Try this:

trigger updateacc on Opportunity (before insert,before update) {   
     for(Opportunity opp : trigger.new){
         if(opp.StageName == 'Qualification' && opp.AccountId !=null){
              Account acc = new Account();
              acc.id = opp.AccountID;
              acc.Rating = 'cold';
              update acc;      
           }
      }
   }
Aman MalikAman Malik
Hi,
Note: We should not perform DML inside for loop. it will lead to hit governer limit.
Please try below snippet:
trigger mapAccount on Opportunity (before insert,before update) {
    
    Set<Id> accId = new Set<Id>();
    for(Opportunity o: Trigger.new){
    	if(o.StageName = 'Qualification' && o.AccountId !=null){
    		accId.add(o.AccountId);
    	}
    }

    List<Account> accList = new List<Account>();
    for(Account ac: accId){
    	accList(new Account(id=ac, rating='Cold'));
    }

    if(!accList.isEmpty()){
    	update accList;
    }
}
Please like the answer and mark it best if this helps.

Thanks,
Aman
Ajay Anikar H RAjay Anikar H R
Hi Soumya,
I would take a step back here to understand why this cannot be accomplished using "Process Builder", unless you have already tried and it is hitting SOQL limits and considering other factors for future proof - like number of recods that would be updated at a given point of time. 

Hope this helps.
Thank you