• Syed Wasim 13
  • NEWBIE
  • 0 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
I have the following Trigger to Update Contact Owner Only when Account Owner Changes however only some of the Contact Owners are being updated. It's not updating any other child records, which is great. I just need to understand why it won't update ALL Contacts on an Account.

trigger Changeownertrigger on Account (after update) {
       
          Set<Id> accountIds = new Set<Id>();
          Map<Id, String> oldOwnerIds = new Map<Id, String>();
          Map<Id, String> newOwnerIds = new Map<Id, String>();
          Contact[] contactUpdates = new Contact[0];
          
          for (Account a : Trigger.new)
          {
             if (a.OwnerId != Trigger.oldMap.get(a.Id).OwnerId)
             {
                oldOwnerIds.put(a.Id, Trigger.oldMap.get(a.Id).OwnerId);
                newOwnerIds.put(a.Id, a.OwnerId);
                accountIds.add(a.Id);
             }

          }
            if (!accountIds.isEmpty()) {
             for (Account acc : [SELECT Id, (SELECT Id, OwnerId FROM Contacts) FROM Account WHERE Id in :accountIds])
                {
                String newOwnerId = newOwnerIds.get(acc.Id);
                String oldOwnerId = oldOwnerIds.get(acc.Id);
                for (Contact c : acc.Contacts)
                {
                   if (c.OwnerId == oldOwnerId) 
                   {
                   Contact updatedContact = new Contact(OwnerId = newOwnerId);
                   contactUpdates.add(updatedContact);
                   }
                }
                 
                }
           }
                update contactUpdates;
    }