This trigger ensures that when the owner of an Account changes, the owners of all related Contacts are updated to match the new Account owner.
Explore similar triggers in this YouTube playlist.
Solution:
trigger AccountTrigger on Account (after update) {
if(Trigger.isUpdate){ if(Trigger.isAfter){
AccountTriggerHandler.updateOwnerOfRelatedContact(Trigger.
new, Trigger.oldMap);
}
}
}
public class AccountTriggerHandler{
public static void updateOwnerOfRelatedContact(List<Id,Account>
accList,Map<Id,Account>oldMap){
List<Contact> conList= new List<Contact>();
Set<Id>idSet= new Set<Id>(); for(Account
acc:accList){
if(acc.OwnerId!=oldMap.get(acc.Id).OwnerId){
idSet.add(acc.Id);
}
}
for(Account acc:[SELECT Id,OwnerId, (SELECT OwnerId FROM
Contacts) FROM Account WHERE Id IN:idSet]){
if(acc.Contacts!=null){ for(Contact c:acc.Contacts){
c.OwnerId=acc.OwnerId;
conList.add(c);
}
}
}
if(!conList.isEmpty()){
update conList;
}
}
}