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
salesforce_hoonigansalesforce_hoonigan 

APEX Help: Populate Lookup Field based on Text field

Hi Experts,

I hope you could assist me creating a code to auto populate a Lookup field based on a Text field. This text field will always contain the ID of a Lead. The custom Object and Lead doesn't have a direct relationship. The text field will be populated manually

Details:
Object: Cloud File (Custom)
Text Field: Text__c (Residing in Cloud File)
Lookup Field: Lead__c

Any assistance is greatly appreciated.
Best Answer chosen by salesforce_hoonigan
Abhishek BansalAbhishek Bansal
Hi,

You can easily achieve this with the help of a workflow rule.
Create a workflow rule and than add a field update in it.

If you want to go with a trigger than please use the below trigger code on Cloud File object :
trigger updateLead on Cloud_File__c (before insert, before update){
	for(Cloud_File__c cloudFile : trigger.new){
		if(cloudFile.Text__c != null){
			cloudFile.Lead__c = cloudFile.Text__c;
		}
	}
}
//Please replace Cloud_File__c with API name of your Cloud File object


Please let  me know if you need more help on this or if you have any issue with the above code.

Thanks,
Abhishek Bansal

All Answers

Abhishek BansalAbhishek Bansal
Hi,

You can easily achieve this with the help of a workflow rule.
Create a workflow rule and than add a field update in it.

If you want to go with a trigger than please use the below trigger code on Cloud File object :
trigger updateLead on Cloud_File__c (before insert, before update){
	for(Cloud_File__c cloudFile : trigger.new){
		if(cloudFile.Text__c != null){
			cloudFile.Lead__c = cloudFile.Text__c;
		}
	}
}
//Please replace Cloud_File__c with API name of your Cloud File object


Please let  me know if you need more help on this or if you have any issue with the above code.

Thanks,
Abhishek Bansal

This was selected as the best answer
salesforce_hoonigansalesforce_hoonigan
Thanks Abhishek,

I don't think workflow rule would work on this since Workflow Rule Field Updates can't dynamically set Lookup() field values and it doesn't allow me to select a lookup field on field updates.

Another question, how can I bulkify that code?

Thank you again for helping me out.
 
Abhishek BansalAbhishek Bansal
Hi,

Yes you are right you cannot set the value of a lookup field from field update.
Answering to your second question, the code provided by me is already bulkified.
Dont be tensed about it and go ahead with my code.

Thanks,
Abhishek
salesforce_hoonigansalesforce_hoonigan
Thank you Abhishek!