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
sfdevnicksfdevnick 

Populate Lookup field with fixed ID on record save

Hi, I'm an apex newbie. I need a trigger to fill the AccountID lookup field on the Contact record with a fixed ID every time a Contact is saved with that field empty. Would the following work?

  

trigger SetAccountField on Contact (before insert, before update) {
    for (Contact contact : Trigger.new) {
        Contact.Account = '0017000000UzTRj';
    }
 }

 

//Where 0017000000UzTRj is the ID of the Account record

 

Do I need to add something to make sure it ONLY does this when the AccountID field is empty? Like  IF(isempty(Contact.Account,..

 

And how would I modify so that it works if Contacts without an Account ID were loaded via the SF import wizards or via the API?

 

Thanks in advance.:smileyhappy:

NaishadhNaishadh

just check for null

 

i.e. if(Contact.Account != null)

    Contact.Account =  '0017000000UzTRj';

sfdevnicksfdevnick
Thank you for your quick response N. I apologize for not responding sooner, I have been off the grid knee deep in alligators working on an unexpected deadline. I'm hoping to be able to resume coding again in a few days, and will test and respond again then. -J