August 1, 2014

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

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)
        mapAccount.put(acct.Id, acct);
   
    listContact = [ SELECT MailingStreet, MailingCity, AccountId FROM Contact WHERE AccountId IN : mapAccount.keySet() ];
   
    if ( listContact.size() > 0 ) {
        for ( Contact con : listContact ) {
            con.MailingStreet = mapAccount.get(con.AccountId).BillingStreet;
            con.MailingCity = mapAccount.get(con.AccountId).BillingCity;
        }
        update listContact;
    }
}


Cheers!!!

5 comments:

  1. Thank you so much . Its really helpful !

    ReplyDelete
  2. Can you please update for same object. Example when updating parent account, related child accounts needs to be updated.

    ReplyDelete
    Replies
    1. For Assets, it's possible with RootAssetId. For account, it is if you have fetch only child accounts(one level only).

      Delete