+ Start a Discussion
Manjunath reddy 25Manjunath reddy 25 

before trigger on opportunity to update the fields in account.

I'm currently trying to create a trigger that runs whenever an Opportunity is created or updated. The trigger needs to check all the other Opportunities related to the Account of the Opportunity being updated. It should check to see if any of the Opportunities have a StageName equal to 'Closed Won ', if so, it should update the account Type to 'Customer'. If none of the Opportunities are closed won, the Account Type should be 'Prospect'.but iam getting accs.get(o.accountId).type as null in debug log.can someone help me on this.
trigger updateAccountIfOppCustomer on Opportunity (before insert, before update) {
    list<opportunity> accOpps = new list<opportunity>();
    list<id>  accountIds = new list<id>();
    
    for(opportunity opp:trigger.new){
        accountIds.add(opp.accountId);
    }
    
    list<opportunity> opps = [select id,AccountId,StageName  from opportunity where accountId IN:accountIds];
    map<id,account> accs = new map<id,account>([select id,type from account where id IN:accountIds]);
    system.debug('accs '+accs );
    for(opportunity o:opps){
            if (o.StageName == 'Closed Won'  || o.StageName == 'Customer Reseller') {
                //acc.type = 'prospect';
                accs.get(o.accountId).type='prospect';
        }
    }
    
}

 
snehal surti 3snehal surti 3
Have you checked whether  opportunity you are trying to test has associated account? This can be one possibility and other whether account found associated with opportunity exists in map or not. Check your accs map and see account exists.

Try this:

(accs.get(o.accountId)).type='prospect';
Manjunath reddy 25Manjunath reddy 25
Thanks  for your help Swaraj, it worked fine, but somewhere I heard that we should not use update DML iwhen we are using before update,but in our case working fine, do you have any idea is that statement correct?