Here's how you can write a trigger in Salesforce to update all related Contacts' HomePhone
field whenever the Phone
field on an Account
is updated. The solution uses Parent-Child SOQL and adheres to best practices.
trigger UpdateContactsOnAccountPhoneChange on Account (after update) {
// Set to hold account IDs where the Phone has been updated
Set<Id> updatedAccountIds = new Set<Id>();
// Collect the IDs of Accounts where Phone has been updated
for (Account acc : Trigger.new) {
Account oldAcc = Trigger.oldMap.get(acc.Id);
if (acc.Phone != oldAcc.Phone) {
updatedAccountIds.add(acc.Id);
}
}
// If no relevant accounts, exit early
if (updatedAccountIds.isEmpty()) {
return;
}
// Query Contacts related to updated Accounts
List<Contact> contactsToUpdate = [
SELECT Id, HomePhone
FROM Contact
WHERE AccountId IN :updatedAccountIds
];
// Prepare the Contacts for update
List<Contact> contactsForUpdate = new List<Contact>();
for (Contact con : contactsToUpdate) {
Account updatedAcc = Trigger.newMap.get(con.AccountId);
con.HomePhone = updatedAcc.Phone; // Set HomePhone to Account Phone
contactsForUpdate.add(con);
}
// Perform the update on related Contacts
if (!contactsForUpdate.isEmpty()) {
update contactsForUpdate;
}
}
Key Points of the Implementation:
Trigger Context:
- The trigger runs on the
Account
object in theafter update
context. - The
after
context is used because we are updating child records (Contact
) based on the changes in the parent record (Account
).
- The trigger runs on the
Change Detection:
- Compare
Trigger.new
andTrigger.old
to detect changes in thePhone
field ofAccount
.
- Compare
Parent-Child SOQL:
- Query
Contact
records where theAccountId
matches the IDs of Accounts with updated Phone numbers.
- Query
Bulkified Code:
- The code handles bulk updates efficiently by processing multiple Accounts and their related Contacts in batches.
Avoid Recursive Triggers:
- Ensure there is no logic in the
Contact
trigger that could lead to recursion when these updates are performed.