Reassigning Contact Owner in Salesforce to Account Owner

Salesforce Snippets

On this blog I'll share any code snippets that I develop in Salesforce.com. 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 Blogger.com to handle code snippets and posting a test trigger.

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

http://geektalkin.blogspot.co.uk/2009/11/embed-code-syntax-highlighting-in-blog.html

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 Salesforce.com 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 : Trigger.new ) {
            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.id, acct.ownerId );
        }
       
        // change contact owner to its account owner
        for ( Contact c : Trigger.new ) {
            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
    }

}


Comments


  1. Thanks for sharing; Salesforce crm cloud application provides special cloud computing tools for your client management problems. It’s a fresh technology in IT industries for the business management. It’s a good option for the fresher to take training get enter in IT field. Salesforce training in Chennai

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. This comment has been removed by a blog administrator.

    ReplyDelete
  6. This comment has been removed by a blog administrator.

    ReplyDelete
  7. This comment has been removed by a blog administrator.

    ReplyDelete
  8. This comment has been removed by a blog administrator.

    ReplyDelete

Post a Comment