+ Start a Discussion
Soumya ChoudhurySoumya Choudhury 

trigger to update related records

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>();
    for(Opportunity o:ol){
        mp.put(o.id, o);

Could someone help me.
Bhanu joshi 10Bhanu joshi 10
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
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){

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

    	update accList;
Please like the answer and mark it best if this helps.

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