+ Start a Discussion
Hugo_BHugo_B 

Need help with trigger to populate a lookup field.

I have a custom object "Time_Entry__C" that has a look-up field called "Employee__C" which holds the ID from an Employee object

  - The employee object has ID, Firstname__C; Lastname__C fields.

 

I want to populate the Employee1__c field (in the Time_Entry__C object) with the ID from the Employee object (SFDC_Employee__c) BASED upon the current user (if found).

 

For example.  The current user = "John Doe"  When he creates a record in the Time_Entry__c object, I want a "before insert"  trigger to find the ID in the SFDC_Employee__c object  where SFDC_Employee__c.firstname = UserInfo.firstname and SFDC_Employee__c.lastname = Userinfo.Lastname then plop that Employee ID into the Employee1__c  lookup field on the Time_Entry__c object.

 

Any help?

Jeremy_nJeremy_n

Before Trigger (since you're modifying the triggered records, using Before is a lot simpler)

 

1. get all first names and last names in 2 set<String> variables (loop through triggered records)

2. Query for Employees with a first name in the first name set and last name in the last name set

3. Go through triggered records, and for each one, look through the list of Employee records until you find a record where First Name and Last Name matches. When that happens, update the Employee__c field on the current triggered record.

 

Good luck,

Jeremy

jnegijnegi

Hi,

You can do it in "before trigger" only.

 

Please find the below steps to achieve the desired functionality:-


1. First get the firstname and lastname of the current user 

 

2. Create a string name = firstname +lastname

 

3. Create a Map(employeeDetailsMap ) in which the key value would be name(firstname +lastname) and value would be the Employee__C id. (Map<String,Id>)

 

4. Make the SOQL query on Employee__c table to store the values in the employeeDetailsMap.

 

5. Now iterate through the Time_Entry__c object using Trigger.new 

 

6. Use  employeeDetailsMap.get(name) to set the id in Employee__c field on Time_Entry__c object.

 

 

Kindly mark it as closed if it resolves your issue.

 

Thanks,

Jagmohan Negi

Noida, India