Sync Contact Owner Using Maps

This trigger achieves the same functionality as entry 50 but uses Map logic for efficient updates when syncing Contact owners with Account owners.

For more examples, visit 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
             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.OwnerId!=oldMap.get(acc.Id).OwnerId){
             accToAccountMap.put(acc.Id,acc);
                         }
              }
             for(Contact con:[SELECT AccountId,OwnerId FROM Contact
             WHERE AccountId IN:accToAccountMap.keySet()]){
                             con.OwnerId=accToAccountMap.get(con.AccountId).OwnerId;
                             conList.add(con);
              }
                             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 :)