• Tim Abramson
  • NEWBIE
  • 0 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
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;
}

 
  • April 15, 2016
  • Like
  • 0