Salesforce’s Web-to-Lead is a great tool to generate leads via HTML forms embedded in any website or app. A Web-to-Lead form is essentially an HTML form that includes our choice of Lead’s fields that we want the user to fill. We can use multiple types of fields in the form in question, However, Salesforce restricts us from using a Lookup field in the Web-to-Lead form. But rest assured, there is a workaround to solve this issue.
In order to populate a Lookup field via the Web-to-Lead form, you must follow the steps mentioned below.
Create a custom Text field
Let’s say our Lookup field on a Lead object is called “Lead Source” which references to an Account record. For this, we would create a custom text field called “Lead Source Text”. This field will only be used in the backend, so no need to display it on the layout.
Add custom Text field in Web-to-Lead form
Now, instead of trying to add the original Lookup field in Web-to-Lead form, add our custom Text field instead. Basically, we would take the ID of the record in String form using this custom Text field.
Write a Trigger on Lead object
In case you haven’t already written a Trigger on the Lead object, you are required to use the Trigger to make this work. Create a new Apex Trigger called “Lead Trigger” and a new class called “LeadTriggerHandler”. Follow the Trigger Handler Pattern for best practices, which is to handle all the logic in the handler and just use the Trigger to call the Handler methods.
In your Trigger Handler, add the following function:
private void convertTextToLeadSource() // Name as per your logic { for(Lead l : (List<Lead>) Trigger.new) { if(Trigger.isInsert && l.Lead_Source_Text__c != null) { // Perform Validation here l.Lead_Source__c = l.Lead_Source_Text__c; } } }
This method checks if a lead is inserted and the Lead Source Text field is filled, then insert the value of the custom text field – that should be a valid ID – to Lead Source (Lookup field). Make sure you perform the required validations in order to check that the input String coming from the Web-to-Lead form represents a valid ID and that ID belongs to an existing record or not.
Write Test Class
Lastly, write the Test Class for your Trigger Handler in order to unit test your functionality and complete the code coverage for deployment purposes.
By following these steps, you can easily populate a Lookup field through the Web-to-Lead form.
Also Read
- How to delete a project in DevOps Center Salesforce?
- Convert Country Code to Country Name in Google Sheets for Data Import Wizard
- How to find Salesforce org type via Apex code?