This trigger checks if an Account’s “Active” field is updated from “Yes” to “No.” It updates all related Opportunities to “Closed Lost” if their Stage is not already “Closed Won.”
For more practice, explore this YouTube playlist.
Solution:
trigger AccountTrigger on Account (after update) {
if(Trigger.isUpdate){ if(Trigger.isAfter){
AccountTriggerHandler.updateOpportunityStage(Trigger.New, Trigger.oldMap);
}
}
}
public class AccountTriggerHandler {
public static void updateOpportunityStage(List
accList,Map<Id,Account> oldMap){
List<Opportunity> oppList=new
List<Opportunity>(); Set<Id> idSet= new Set<Id>(); for(Account
acc:accList){ if(acc.Active__c == ‘No’
&& acc.Active__c !=
oldMap.get(acc.Id).Active__c){ idSet.add(acc.Id);
}
}
for(Account a:[SELECT Id,Active__c,(SELECT Id,StageName FROM
Opportunities) FROM Account WHERE Id IN:idSet]){
if(acc.Opportunities!=null){ for(Opportunity opp:a.Opportunities){
if(opp.StageName!=’Closed
Won’&&opp.StageName!=’Closed Lost’){ opp.StageName=’Closed Lost’;
oppList.add(opp);
}
}
}
} if(oppList.size( ) > 0){ update oppList;
}
}
}