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;
}
}
}