Update Contact Phone with Account Phone

When an Account’s Phone field is updated, this trigger propagates the change to the Home Phone field of all related Contacts using Map logic for efficiency.

Practice similar use cases 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
                 updateRelatedConts(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.Phone!=null
                                                && acc.Phone!=(oldMap.get(acc.Id).Phone))
                                                && oldMap!=null){
                                                accToAccountMap.put(acc.Id,acc);
                      }
}
      for(Contact cont:[SELECT Id, HomePhone, AccountId FROM Contact
                    WHERE AccountId IN: accTOAccountMap.keySet()]){
                          if(accToAccountMap.containsKey(cont.AccountId)){
                                     cont.HomePhone=accToAccountMap.get(cont.AccountId).
                                      Phone;
                                      conList.add(cont);
                     }
                                   } if(!conList.isEmpty()){ update
                                                conList;
                 }
                   OR
                           if(conList.size() > 0){ 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 :)