Here's how you can write a Salesforce trigger to update related Contacts' MailingAddress
fields when the BillingAddress
of an Account
is updated. This implementation uses Parent-Child SOQL.
trigger UpdateContactsOnAccountBillingAddressChange on Account (after update) {
// Collect Account IDs where the Billing Address has changed
Set<Id> updatedAccountIds = new Set<Id>();
for (Account acc : Trigger.new) {
Account oldAcc = Trigger.oldMap.get(acc.Id);
if (acc.BillingStreet != oldAcc.BillingStreet ||
acc.BillingCity != oldAcc.BillingCity ||
acc.BillingState != oldAcc.BillingState ||
acc.BillingPostalCode != oldAcc.BillingPostalCode ||
acc.BillingCountry != oldAcc.BillingCountry) {
updatedAccountIds.add(acc.Id);
}
}
// Exit if no Billing Address changes detected
if (updatedAccountIds.isEmpty()) {
return;
}
// Query Accounts with their related Contacts
List<Account> accountsWithContacts = [
SELECT Id, BillingStreet, BillingCity, BillingState, BillingPostalCode, BillingCountry,
(SELECT Id, MailingStreet, MailingCity, MailingState, MailingPostalCode, MailingCountry FROM Contacts)
FROM Account
WHERE Id IN :updatedAccountIds
];
// Prepare Contacts for update
List<Contact> contactsToUpdate = new List<Contact>();
for (Account acc : accountsWithContacts) {
for (Contact con : acc.Contacts) {
// Update Mailing Address on Contact
con.MailingStreet = acc.BillingStreet;
con.MailingCity = acc.BillingCity;
con.MailingState = acc.BillingState;
con.MailingPostalCode = acc.BillingPostalCode;
con.MailingCountry = acc.BillingCountry;
contactsToUpdate.add(con);
}
}
// Update Contacts in bulk
if (!contactsToUpdate.isEmpty()) {
update contactsToUpdate;
}
}
Key Features:
Parent-Child SOQL:
- Queries
Account
records with their relatedContact
records using a subquery.
- Queries
Change Detection:
- Compares the old and new
BillingAddress
fields ofAccount
records to detect changes.
- Compares the old and new
Bulk Handling:
- Efficiently handles multiple Accounts and their related Contacts in a single transaction.
Exit Early:
- Avoids unnecessary operations when no relevant changes are detected.
Minimal SOQL/DML:
- Uses one SOQL query to fetch all necessary data and performs a single DML update operation.