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
Steve Cairney NOWSteve Cairney NOW 

Trigger that will pull the Record ID of a distant object based on the record name to create lookup relationship

Hi, I'm trying to fill out lookup relationship field on one object using the name (auto number) of another.

I've tried process builder but I don't think it's possible so I'm thinking a trigger is whats needed.

Example,

The main object is called Patient__c has each record will have a name such as PAT-1234
The second object is called Prescription__c and using API (not my department) and that has lookup field for Patient__c and a field called SFPatientREF__c which is filled in PAT-1234. This is done on insert with the API

To connect the two, I need to popute the look up field with the ID of PAT-1234 so would it be possible to pull this into a feild called SFPatientID__c and have process builder to the rest?
NitishNitish
Hi Steve,

Please try the below code. I hope it will work.
Trigger insertPrescription on Prescription__c (before insert){
	Map<String,Id> patMap=new Set<String,Id>();
	List<Patient__c > patList=[SELECT Id,Name FROM Patient__c];
	for(Patient__c  p:patList){
			patMap.put(p.Name,p.Id);
	}
	for(Prescription__c pre:Trigger.new){
		if(patMap.containskey(pre.SFPatientREF__c )){
			pre.SFPatientID__c = patMap.get(pre.SFPatientREF__c);
		}
	}
	
	
}