+ Start a Discussion
Anthony GarandAnthony Garand 

Where to place trigger trigger reassignContactOwnerToAccountOwner on Contact ( before insert, before update )

Hello Everyone,

Pretty simple question, I have this apex trigger ready to go; But I am unsure where to place it. It updates contacts and opportunity owners to match the account owner, So I am assuming I put it under the account triggers? 
Here is the code.

trigger reassignContactOwnerToAccountOwner on Contact ( before insert, before update ) {

    List<Id> accountIds = new List<Id>();
    Map<Id, Id> accountOwnerIdMap = new Map<Id, Id>();

    // all the accounts whose owner ids to look up
    for ( Contact c : Trigger.new ) {
        accountIds.add( c.accountId );
    }
    
    // look up each account owner id
    for ( Account acct : [ SELECT id, ownerId FROM account WHERE id IN :accountIds ] ) {
        accountOwnerIdMap.put( acct.id, acct.ownerId );
    }
    
    // change contact owner to its account owner
    for ( Contact c : Trigger.new ) {
        c.ownerId = accountOwnerIdMap.get( c.accountId );
    }
   
}

 
Abhishek M.Abhishek M.
You can save the trigger as it is.
It should be on contact which is correct, but as per your description this will only update the Contact's owner and not Oppotunity's.

But you might want to write another trigger on Account, such that if the Account owner changes, then its related contact's owner should be updated.