Here is a Salesforce trigger implementation that updates related Contacts' MailingAddress
whenever the BillingAddress
of an Account
is updated, using a Map to handle data efficiently.
trigger UpdateContactsOnBillingAddressChange on Account (after update) {
// Map to store updated Account IDs and their Billing Address
Map<Id, Account> accountsWithUpdatedAddress = new Map<Id, Account>();
// Identify Accounts where Billing Address has changed
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) {
accountsWithUpdatedAddress.put(acc.Id, acc);
}
}
// Exit if no Billing Address has been updated
if (accountsWithUpdatedAddress.isEmpty()) {
return;
}
// Query related Contacts for these Accounts
List<Contact> contactsToUpdate = [
SELECT Id, MailingStreet, MailingCity, MailingState, MailingPostalCode, MailingCountry, AccountId
FROM Contact
WHERE AccountId IN :accountsWithUpdatedAddress.keySet()
];
// Update the Mailing Address on Contacts
List<Contact> contactsForUpdate = new List<Contact>();
for (Contact con : contactsToUpdate) {
Account acc = accountsWithUpdatedAddress.get(con.AccountId);
// Update Mailing Address fields
con.MailingStreet = acc.BillingStreet;
con.MailingCity = acc.BillingCity;
con.MailingState = acc.BillingState;
con.MailingPostalCode = acc.BillingPostalCode;
con.MailingCountry = acc.BillingCountry;
contactsForUpdate.add(con);
}
// Perform the update operation
if (!contactsForUpdate.isEmpty()) {
update contactsForUpdate;
}
}
Key Features of the Trigger:
Efficient Map Usage:
- A
Map<Id, Account>
stores Accounts with updatedBillingAddress
for quick reference during Contact updates.
- A
Field Change Detection:
- Compares
BillingStreet
,BillingCity
,BillingState
,BillingPostalCode
, andBillingCountry
fields betweenTrigger.new
andTrigger.old
.
- Compares
Bulk Handling:
- Processes multiple Accounts and their Contacts in bulk to ensure scalability.
Exit Early:
- If no relevant Accounts are identified, the trigger exits to avoid unnecessary operations.
SOQL Optimization:
- Queries only the necessary Contacts related to Accounts with updated Billing Addresses.