function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
BobBob 

Updating Contact Owner with Account Owner

I need a trigger that will update the contact owner to match the account owner when a contact is created. Can anyone help with some code?

Best Answer chosen by Admin (Salesforce Developers) 
Scott_VSScott_VS
trigger SetContactOwner on Contact (before insert) {
    // Gather accounts
    List<String> accountList = new List<String>();
    for (Contact c : Trigger.new)
        accountList.add(c.AccountId);
    
    // Query Accounts
    Map<Id, Account> accountMap = new Map<id, Account>([SELECT OwnerId FROM Account WHERE id =: accountList]);
    
    // Set Owners
    for (Contact c : Trigger.new){
        Account a = accountMap.get(c.AccountId);
        if (a != null)
            c.OwnerId = a.OwnerId;
    }
}

 

All Answers

Scott_VSScott_VS
trigger SetContactOwner on Contact (before insert) {
    // Gather accounts
    List<String> accountList = new List<String>();
    for (Contact c : Trigger.new)
        accountList.add(c.AccountId);
    
    // Query Accounts
    Map<Id, Account> accountMap = new Map<id, Account>([SELECT OwnerId FROM Account WHERE id =: accountList]);
    
    // Set Owners
    for (Contact c : Trigger.new){
        Account a = accountMap.get(c.AccountId);
        if (a != null)
            c.OwnerId = a.OwnerId;
    }
}

 

This was selected as the best answer
BobBob

Thanks Scott, it worked perfectly. Much appreciated!  I'll be sure to read your coding tips on your blog.

 

Thanks again.

Erica ThomasErica Thomas
This worked for me too. Thanks Scott!