User Story
As a Salesforce administrator, I want to ensure that when the owner of an account is changed, the owner of all related contacts is also updated automatically. This will help ensure that the correct sales representative is assigned to all contacts associated with the account.
Code
trigger updateContactOwnerOnAccountOwnerChange on Account (after update) {
Set<Id> accountIds = new Set<Id>();
for(Account acc : Trigger.new){
if(acc.OwnerId != Trigger.oldMap.get(acc.Id).OwnerId){
accountIds.add(acc.Id);
}
}
List<Contact> contactsToUpdate = new List<Contact>();
for(Contact con : [SELECT Id, AccountId, OwnerId FROM Contact WHERE AccountId IN :accountIds]){
con.OwnerId = Trigger.newMap.get(con.AccountId).OwnerId;
contactsToUpdate.add(con);
}
if(!contactsToUpdate.isEmpty()){
update contactsToUpdate;
}
}
Video
Video does not exists.