Development questions
When a Contact's Primary_Phone__c is updated on the primary Contact, sync that phone number up to the parent Account's Phone field.
Use after insert, after update on Contact. When a primary Contact's Primary_Phone__c changes, copy it to the parent Account.
apex
trigger ContactTrigger on Contact (after insert, after update) {
Map<Id, Account> toUpdate = new Map<Id, Account>();
for (Contact c : Trigger.new) {
if (c.Is_Primary__c && c.AccountId != null &&
(Trigger.isInsert || c.Primary_Phone__c != Trigger.oldMap.get(c.Id).Primary_Phone__c)) {
toUpdate.put(c.AccountId, new Account(Id = c.AccountId, Phone = c.Primary_Phone__c));
}
}
if (!toUpdate.isEmpty()) update toUpdate.values();
}
Using a Map keyed by AccountId avoids duplicate-Id errors in the update list.
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?