Sync Contact Mailing Address with Account Billing

This trigger updates the Mailing Address of all Contacts when an Account’s Billing Address is modified, ensuring data consistency.

Learn about similar automation here: YouTube playlist.

Solution:

trigger AccountTrigger on Account (after update) {
           if(Trigger.isUpdate){ if(Trigger.isAfter){
                                         AccountTriggerHandler.updateRelatedConts(Trigger.New, Trigger.oldMap);
                           }
           }
}
public class AccountTriggerHandler { public static void
         updateRelatedContactMail(List<Account> accList,Map<Id,Account> oldMap){
                         List<Contact> conList=new List<Contact>();
                         Map<Id,Account> accToAccountMap= new Map<Id,Account>();
             for(Account acc:accList){ if( (!acc.BillingCity.equals(oldMap.get(acc.Id).BillingCity) ||
                     !acc.BillingCountry.equals(oldMap.get(acc.Id).BillingCountry) ||
                     !acc.BillingPostalCode.equals(oldMap.get(acc.Id).BillingPostalC
                     ode) ||c!acc.BillingState.equals(oldMap.get(acc.Id).BillingState)
                                     || !acc.BillingStreet.equals(oldMap.get(acc.Id).BillingStreet) )
                     && oldMap!=null){
                                  accToAccountMap.put(acc.Id,acc);
                      }
      }
      for(Contact con:[SELECT Id,AccountId FROM Contact WHERE
      AccountId IN: accTOAccountMap.keySet()]){
       if(accToAccountMap.containsKey(cont.AccountId)){
                  con.MailingCountry = accToAccountMap.get(cont.AccountId).BillingCountry;
                     con.MailingCity =
                          accToAccountMap.get(cont.AccountId).BillingCity;
                          con.MailingState = accToAccountMap.get(cont.AccountId).BillingState;
                           con.MailingPostalCode = accToAccountMap.get(cont.AccountId).BillingPostalCode;
                            con.MailingStreet =
                            accToAccountMap.get(cont.AccountId).BillingStreet;
                            conList.add(con);
               }
      } if(!conList.isEmpty()){ update
         conList;
          }
     }
}

Want to Apply As Content Writer?

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart

Let's get you started!

Interested in writing Salesforce Content?

Fill in this form and we will get in touch with you :)