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
pacstratspacstrats 

How to use Trigger to update Lookup field

I'm somewhat familiar with Triggers but I'm having a hard time with this one, and I'm not even sure it can be done.

Since I can't use workflows to automatically update a lookup field, I want to create a Trigger to update the lookup field of a standard object (Lead) with the ID/Name of a custom object (Employee) based on the value of a custom field within the Lead object.

In short, my Employee object is related to Leads and I'd like the trigger to use the value of the custom field (EmployeeName__c) in Lead to query the Name field in the Employee custom object to retrieve and store the ID of the Employee record in the lookup field within Leads called Employee__c.

Any thoughts?

T
camy2079camy2079
Great question, I'm looking to do this as well. Please re-post if you find out how.
pacstratspacstrats
Here is what I figured out last night:

trigger EmployeeUpdate on Lead (before insert, before update) {
List EmployeeName = new List();
for (Integer i = 0; i < Trigger.new.size(); i++)
{
EmployeeName.add(Trigger.new[i].EmployeeName__c);
}
List EmployeeList = new List([Select Id from Employee__c where Name in :EmployeeName]);
for (Integer i = 0; i < Trigger.new.size(); i++)
{
if (Trigger.new[i].EmployeeName__c != null)
{
Trigger.new[i].Employee__c = EmployeeList[i].Id;
}
else
{
Trigger.new[i].Employee__c = null;
}
}
}

I've tested it and it seems to work just fine. Good luck!
salesforcesaintsalesforcesaint

Hi, I am very new to Apex. Just took the DEV 531 class and understand how the code is set up, but am struggling to write my own. :(

 

Your post is the closest to what I am trying to do. Can you tell me how I can modify your code to update the primary campaign source (lookup field) in an opportunity to a specific campaign, IF a custom picklist (also on the opportunity) has a certain value?

 

Thank you!