+ Start a Discussion
SambitNayakSambitNayak 

Trigger to update an Account everytime a related Opportunity's stage changes

Hi,
I need to add a description on my Account every time an Opportunity's stage is changed.
I tried the following and getting NULL pointer exception. Please help:

 

public class opportunityTriggerHandler {
    public static void oppStgChangeDetails(List<Opportunity> oppList, map<Id,Opportunity>oldmap, boolean isInsert, boolean isUpdate){
        List<Account> accsToUpdate = New List<Account>();

for(Opportunity opp:oppList){
            if(isInsert || (isUpdate && opp.stageName <> oldmap.get(opp.Id).stageName)){
                opp.Account.Description = opp.Account.Description + 'Prev Stage: ' +oldmap.get(opp.Id).stageName 
                    + 'New Stage: '+opp.StageName;
                accsToUpdate.add(opp.Account);
            }
        }
        update accsToUpdate;
    }
}

Best Answer chosen by SambitNayak
PriyaPriya (Salesforce Developers) 
Hey 

Kindly try like below :- 
trigger updateAccountRating on opportunity (after insert, after update){
	list<Id> accIds = new list<Id>();
	list<Account> accounts = new list<account>();
	for(opportunity o:trigger.new){
		accIds.add(o.accountId);
	}
	for(account a:[select Id, Rating from account where Id IN :accIds]){
		for(opportunity opp:trigger.new){
			if(opp.stage=='closed won'){
				a.Description='some information';
				accounts.add(a);
			}
		}
	}
    update accounts;
}

 

kindly mark it as the best answer if it helps.

Thank you,

Priya Ranjan

All Answers

PriyaPriya (Salesforce Developers) 
Hey 

Kindly try like below :- 
trigger updateAccountRating on opportunity (after insert, after update){
	list<Id> accIds = new list<Id>();
	list<Account> accounts = new list<account>();
	for(opportunity o:trigger.new){
		accIds.add(o.accountId);
	}
	for(account a:[select Id, Rating from account where Id IN :accIds]){
		for(opportunity opp:trigger.new){
			if(opp.stage=='closed won'){
				a.Description='some information';
				accounts.add(a);
			}
		}
	}
    update accounts;
}

 

kindly mark it as the best answer if it helps.

Thank you,

Priya Ranjan

This was selected as the best answer
SambitNayakSambitNayak
@Priya Ranjan: Thanks for your answer. Working perfect!!