Reassigning Contact Owner in Salesforce to Account Owner

Salesforce Snippets

On this blog I'll share any code snippets that I develop in It'll be a good reminder for me, and I hope it helps other people out there who might come across similar challenges.

Getting started

Right, first challenge of the day - setting up to handle code snippets and posting a test trigger.

That turns out to be quite straightforward thanks to a great post from Geektalkin - thanks!

Right, now that I can copy in Trigger code and maintain it's formatting here's the first example:

What does this trigger do?

This trigger changes the ownership of any Contact record in Salesforce that is added or updated. The trigger ensures that all of the Contacts relating to an account are owned by the Account Owner.

Original source:

This is a slightly modified version of an example trigger posted on the success community.

//Reassigns Contact to Account Owner

trigger reassignContact on Contact (before insert, before update) {
   try {

        Set<Id> accountIds = new Set<Id>();
        Map<Id, Id> accountOwnerIdMap = new Map<Id, Id>();
        // all the accounts whose owner ids to look up
        for ( Contact c : ) {
            if(c.accountId <> null){
             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.ownerId );
        // change contact owner to its account owner
        for ( Contact c : ) {
            if(c.AccountId <> null){
             c.ownerId = accountOwnerIdMap.get( c.accountId );
    } catch(Exception e) { //catch errors
        System.Debug('reassignContacts failure: '+e.getMessage()); //write error to the debug log