Using Parent-Child SOQL queries, this trigger updates all related Contacts’ Home Phone fields when an Account’s Phone field changes.
Explore more scenarios via this 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 updateRelatedContsWithoutMap(List<Account> accList,Map<Id,Account> oldMap){
List<Contact> conList=new List<Contact>(); Set<Id> accIds = new
Set<Id>(); for(Account acc:accList){ if((acc.Phone!=null &&
acc.Phone!=(oldMap.get(acc.Id).Phone))
&& oldMap!=null){ accIds.add(acc.Id);
}
}
for(Account acc : [SELECT Id, Phone, (SELECT HomePhone FROM
Contacts) FROM Account WHERE Id IN:
accIds]){ if(acc.Contacts != null){
for(Contact con : acc.Contacts){ con.HomePhone=acc.Phone;
conList.add(con);
}
}
} if(!conList.isEmpty()){ update
conList;
}
}
}