Development questions
When an Account's OwnerId changes, change the OwnerId of all its related open Opportunities and Contacts.
Use after update on Account, detect OwnerId changes, then update related open Opportunities and Contacts.
apex
trigger AccountTrigger on Account (after update) {
Map<Id, Id> newOwner = new Map<Id, Id>();
for (Account a : Trigger.new) if (a.OwnerId != Trigger.oldMap.get(a.Id).OwnerId) newOwner.put(a.Id, a.OwnerId);
if (newOwner.isEmpty()) return;
List<SObject> toUpdate = new List<SObject>();
for (Opportunity o : [SELECT Id, AccountId FROM Opportunity WHERE AccountId IN :newOwner.keySet() AND IsClosed = false]) {
o.OwnerId = newOwner.get(o.AccountId); toUpdate.add(o);
}
for (Contact c : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :newOwner.keySet()]) {
c.OwnerId = newOwner.get(c.AccountId); toUpdate.add(c);
}
update toUpdate;
}
Note: updating a mixed List<SObject> works when records are sorted by type; otherwise split into two lists to avoid chunk limits.
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?