[SalesForce] How to change opportunities stageName depending on account status

I need to change opportunity stageName depending on account status, if it's active or inactive. If it's inactive stageName needs to be changed to 'Closed Lost'. Otherwise, if the stageName is 'Closed Won' it doesn't need to change. We've been tying with this code but it doesn't work.

trigger OpportunityUpdate on Account (before insert,before update) {
    for(Account a : Trigger.new){
        if(a.Active__c == 'No'){
            Opportunity o = new Opportunity();
            if(o.StageName != 'Closed Won'){
                o.StageName = 'Closed Lost';
            }
        }
    }
}

Best Answer

There is no need for writing trigger on before insert. use only update event

trigger OpportunityUpdate on Account ( after update) {
    set<Id> setAccountId = new set<Id>();
    for(Account a : Trigger.new){
        if(a.Active__c == 'No'){
            setAccountId.add(a.Id);
        }
    }
    List<Opportunity> lstOpportunity = [SELECT Id, StageName FROM Opportunity WHERE AccountId IN: setAccountId];
    for(Opportunity objOpp: lstOpportunity)
    {
        if(objOpp.StageName != 'Closed Won'){
                objOpp.StageName = 'Closed Lost';
        }
    }
    update lstOpportunity;
}
Related Topic