User Story
As a Salesforce Administrator,
I want to ensure that when an Account is deactivated, Opportunities associated with that Account are updated to 'Closed Lost', So that our Opportunity stages accurately reflect the status of active Accounts.
Code
Apex Trigger
trigger Triggers46 on Account (after update) {
UpdateOpportunityStagesHandler.handle(Trigger.new, Trigger.oldMap);
}
Apex Handler Class
public class UpdateOpportunityStagesHandler {
public static void handle(List<Account> newAccounts, Map<Id, Account> oldAccountMap) {
Set<Id> accountIdsToUpdate = new Set<Id>();
for (Account acc : newAccounts) {
if (acc.Active__c == 'No' && oldAccountMap.get(acc.Id).Active__c == 'Yes') {
accountIdsToUpdate.add(acc.Id);
}
}
if (!accountIdsToUpdate.isEmpty()) {
List<Opportunity> oppList =[SELECT Id, StageName FROM Opportunity WHERE AccountId IN :accountIdsToUpdate AND StageName != 'Closed Won'];
List<Opportunity> oppsToUpdate = new List<Opportunity>();
for (Opportunity opp : oppList) {
opp.StageName = 'Closed Lost';
oppsToUpdate.add(opp);
}
update oppsToUpdate;
}
}
}
Video
Video does not exists.