+ Start a Discussion
BobBob 

Trigger Change Contact Owner not working on a new account creation

I have a after insert after update trigger that works when you change the account owner on existing accounts and contacts. But when I try to create a new account, I get the following error message. Apex trigger Trigger_ChangeContactOwner caused an unexpected exception, contact your administrator: Trigger_ChangeContactOwner: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: (). I can't seem to find out where the error is coming from on my trigger. Any help on this would be greatly appreciated.
 
trigger Trigger_ChangeContactOwner on Account (after insert, 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(Id = c.Id, OwnerId = newOwnerId);
               contactUpdates.add(updatedContact);
               }
            }
            
            }
       }
            update contactUpdates;
}

 
Tim AbramsonTim Abramson
Hey Bob,

Since the account is new there likely aren't any Contacts associated with it on Insert, try just using after update.  Also try isolating the update statement to prevent it from hitting the update contactUpdates; like this in case the account is updated and there still aren't contacts to transfer.

       if(contactUpdates.size() > 0){
           update contactUpdates;
       }