Development questions
When an Account is marked Inactive__c = true, automatically close all related open Cases and mark open Opportunities as Closed Lost.
Use after update on Account, detect Inactive__c changing to true, and update related Cases and Opportunities in bulk.
apex
trigger AccountTrigger on Account (after update) {
Set<Id> inactive = new Set<Id>();
for (Account a : Trigger.new) if (a.Inactive__c && !Trigger.oldMap.get(a.Id).Inactive__c) inactive.add(a.Id);
if (inactive.isEmpty()) return;
List<Case> cases = [SELECT Id FROM Case WHERE AccountId IN :inactive AND IsClosed = false];
for (Case c : cases) c.Status = 'Closed';
List<Opportunity> opps = [SELECT Id FROM Opportunity WHERE AccountId IN :inactive AND IsClosed = false];
for (Opportunity o : opps) o.StageName = 'Closed Lost';
update cases; update opps;
}
For large volumes, hand off to Queueable or Batch Apex.
apex-triggertriggercodingscenario
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?