Development questions
When an Account's BillingCity is updated, update the MailingCity on all its related Contacts.
Use after update on Account, filter accounts whose BillingCity changed, then query and update their Contacts.
apex
trigger AccountTrigger on Account (after update) {
Map<Id, String> cityByAcc = new Map<Id, String>();
for (Account a : Trigger.new) {
if (a.BillingCity != Trigger.oldMap.get(a.Id).BillingCity) cityByAcc.put(a.Id, a.BillingCity);
}
if (cityByAcc.isEmpty()) return;
List<Contact> cons = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :cityByAcc.keySet()];
for (Contact c : cons) c.MailingCity = cityByAcc.get(c.AccountId);
update cons;
}
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?