Sync Contact Owner with Account Owner

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

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 :)