How to update child records when parent record is updated in Salesforce?

How to update child records when parent record is updated in Salesforce?

In the below example, when the Account’s Billing Street or City gets updated, it’s related Contacts Mailing Street and City are updated from Account’s Billing Street and City.
 
Sample trigger:
 
trigger ContactUpdate on Account (after update) {    Map <  Id,  Account > mapAccount = new Map < Id, Account >();
List < Contact > listContact = new List< Contact >();

for ( Account acct : trigger.new ) {

/* Checking whether Account’s Billing Street or City Changed */

if ( acct.BillingStreet != trigger.oldMap.get( acct.Id ).BillingStreet ||
acct.BillingCity != trigger.oldMap.get( acct.Id ).BillingCity )
mapAccount.put( acct.Id, acct );

}

if ( mapAccount.size() > 0 ) {

/* Fetching all the contacts related to the update accounts */
listContact = [ SELECT MailingStreet, MailingCity, AccountId FROM Contact WHERE AccountId IN : mapAccount.keySet() ];

if  ( listContact.size() > 0  )  {

for  (  Contact con : listContact  )  {

/* Updating Contact’s Mailing Street and City from Account’s Billing Street and City */
con.MailingStreet = mapAccount.get( con.AccountId ).BillingStreet;
con.MailingCity = mapAccount.get( con.AccountId ).BillingCity;

}
update listContact;

}

}

}

Output:
 
Account:
Contacts:


Leave a Reply