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
JoannaAtMaritzJoannaAtMaritz 

Need Help with Super Simple Trigger on the Contact Object

I have a custom lookup field to the User object on the Contact object called ContactOwner__c.  I need a trigger that can populate this with the contact's owner data upon insert and update.  This will be my first trigger, and I would appreciate some help with the syntax.

 

I'm thinking it should be something like this, but I'm not sure of the syntax to specify to indicate the current record that the trigger is firing on.  Also, does it matter if the event is "before" or "after" for this scenario?  Right now I have it set to "before".

 

trigger SetContactOwner on Contact (before insert, before update) {
thisContact.ContactOwner__c = thisContact.Owner;

}

 

Any help would be greatly appreciated.  Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
JoannaAtMaritzJoannaAtMaritz

Nevermind.  I should have had more patience.  This code seems to work.

 

trigger SetContactOwner on Contact (before insert, before update) {
for (Contact TempContact: System.Trigger.new) 
    {  
        TempContact.ContactOwner__c = TempContact.OwnerId;           
    }

}

All Answers

JoannaAtMaritzJoannaAtMaritz

Nevermind.  I should have had more patience.  This code seems to work.

 

trigger SetContactOwner on Contact (before insert, before update) {
for (Contact TempContact: System.Trigger.new) 
    {  
        TempContact.ContactOwner__c = TempContact.OwnerId;           
    }

}
This was selected as the best answer
NBlasgenNBlasgen

Let's say someone changes the ownership of the contact.  Your code will fire prior to the change.  Might as well do it after the update.

 

You can also have it fire only when there has been a change in ownership.  If the ContactOwner__c == '' or if they're changing the owner, only then fire the trigger.  Otherwise you're updating a field that doesn't need to be updated every single time.