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
Scott2014Scott2014 

How to use a workflow/trigger to update Lookup field

I am attempting to create a workflow/trigger that will update a lookup field with information that comes from a text field when the lookup field doesn't match or is blank.  I read that this is not possible via workflow rule but not 100% sure that is accurate.   

FYI - I have no experience creating a trigger but would like to learn.  This is also my first discussion posting :).   

Anyone thoughts or suggestions ? 
Ramu_SFDCRamu_SFDC
You are right we cannot use workflow rules field update for lookup field updates. Instead you can use the triggers to do the job. All you need to do is have the text field hold ID of the record that needs to be updated on the lookup field. Below is a sample trigger that I wrote on my org for your understanding

In the below trigger
** Accountid_text__c is a custom text field on Travel__c custom object that holds the account id value
** Account__c is a custom lookup field

trigger Travel33 on travel__c (before insert,before update) {
     for(travel__c travels:trigger.new){
        if(travels.accountid_text__c!=null){
            travels.account__c=travels.accountid_text__c;
     
        }
    }
}

Hope this helps !!
Scott2014Scott2014
Alright, thank you for you feedback! 

So, I am trying to create a trigger on the Account record in which the NAICS Code (field name: NaicsCode - from Data.com) updates our custom object NAICS (field name: NAICS_Code__c) anytime the custom object field is blank or different than what Data.com text field indicates. 

Does the below seem like it would work?  If not, can you point out where it may be incorrect?  It probabaly needs another if statement if they aren't equal, correct? 

trigger NAICS on Account (before insert,before update) {
     for(NAICS_Code_C naics:trigger.new){
        if(Naics!=null){
            Account.NAICS_Code__c=Naics;
     
        }
    }
}