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
Christopher MilnerChristopher Milner 

Populate New Lookup Field with Text Data

I have a custom object (titled "Workfront") we are using to track customer onboarding projects. Data from this is being synced over from an outside program and the field we are using to record the name of the trainer ("Implementation Specialist") is coming across as text.

I would like to create a contact lookup field on the object and somehow populate that field with what is in the text field. i.e. if the text field says "John Doe" and we have a contact named "John Doe", I would like to somehow grab the text value, perform a search, and populate the lookup field with a matching contact (if one is found). Any insight on achieving this would be greatly appreciated!
Karthikeyan Rajendran 14Karthikeyan Rajendran 14
Hi Christopher Milner

       You can achieve this in a trigger on Workfront object. Here is the code to implement it.
trigger workFrontTrigger on WorkFront__c (before insert){

	WorkFrontTriggerHandler handler = new WorkFrontTriggerHandler();
	if(Trigger.isBefore && Trigger.isInsert){
		handler.beforeInsertProcess(Trigger.new);
    }
}


public class WorkFrontTriggerHandler {

	public void beforeInsertProcess(List<WorkFront__c> workFrontList){

		List<String> specialistList = new List<String>();
		Map<String,Id> contactMap = new Map<String,Id>();

		for(WorkFront__c work : workFrontList){
			//Implementation Specialist
			//Here I assume the Implementation specialist is a combination of FirstName and LastName
			specialistList.add(work.ImplementationSpecialist__c)
		}

		//becoz of the assumption I am comparing it against Name field
		for(Contact con : [Select Id, Name From Contact Where Name IN: specialistList]){

			//I assume that all your contacts are unique (no two contacts have same name). if it does then you need to pick the right one with additional conditions
			contactMap.put(con.Name, con.Id);
		}

		for(WorkFront__c wk : workFrontList){

			if(contactMap.containsKey(wk.ImplementationSpecialist__c)){
				//Lookup field for contact
				wk.Contact__c = contactMap.get(wk.ImplementationSpecialist__c);
			}
		}
	}
}
I hope the above solution is helpful for you.

Regards
Karthik