August 1, 2014

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:
 

 

9 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
  3. How to implement this trigger for after insert. I want child record to be updated with another parent record if field value does not matches with current parent record
    Please suggest

    ReplyDelete
    Replies
    1. Use after insert event.
      Get the child records using SOQL and update it accordingly by iterating it inside a for loop. Use a list variable to add the changes and update it after the for loop.

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. You cannot use Policy__r.District_Acct_Code__c and Account_Transfer__r.District_From__c without querying it. So, you are getting null pointer exception.

      Delete