How to Add a Filter to a Lookup Field in Microsoft Dynamics CRM
In Microsoft Dynamics CRM, there are times when you need to filter the records displayed in a lookup field to show only a subset of the data. This can be achieved using JavaScript to add a pre-search filter. In this blog, we'll walk you through the steps to filter active contacts in a lookup field.
Step-by-Step Guide
Step 1: Create a JavaScript Web Resource
-
Navigate to CRM:
Go to your Dynamics CRM environment.
-
Open the Solution:
Open the solution where you want to add the JavaScript.
-
Add a Web Resource:
- Go to the "Web Resources" section.
- Click on "New" and create a new JavaScript web resource.
-
Add the JavaScript Code:
Copy and paste the following JavaScript code into your new web resource:
function setActiveContactsFilter(executionContext) { var formContext = executionContext.getFormContext(); var contacts = formContext.getControl("new_activecontacts"); contacts.addPreSearch(filterActiveContacts); } function filterActiveContacts() { var fetchXml = [ "<filter type='and'>", " <condition attribute='statuscode' operator='eq' value='1' />", // Adjust the value based on your status code for 'Active' "</filter>" ].join(''); // Get the lookup control var lookupControl = Xrm.Page.getControl("new_activecontacts"); // Fetch the view ID and entity name var viewId = "{00000000-0000-0000-0000-000000000000}"; // Replace with the actual view ID if required var entityName = "contact"; // Replace with the actual entity name if different // Create the view var viewDisplayName = "Filtered Active Contacts"; var viewIsDefault = true; var layoutXml = ""; // Define the layout XML if needed // Add the view lookupControl.addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, viewIsDefault); }
Save and publish the web resource.
Step 2: Add the JavaScript Web Resource to the Form
-
Open the Form:
Open the form where you want to add the lookup filter.
-
Form Properties:
Click on "Form Properties".
-
Add the Web Resource:
- In the "Form Libraries" section, add the JavaScript web resource you created.
- In the "Event Handlers" section, add an event handler for the
OnLoad
event. - Set the function name to
setActiveContactsFilter
. - Ensure "Pass execution context as first parameter" is checked.
-
Save and Publish:
Save and publish your form changes.
Step 3: Test the Lookup Filter
-
Open the Form:
Navigate to the form where you applied the changes.
-
Verify the Lookup Field:
Click on the lookup field and verify that it now only displays active contacts.
Conclusion
Adding a filter to a lookup field in Microsoft Dynamics CRM can significantly enhance the user experience by ensuring that users only see relevant records. By following the steps outlined above, you can easily implement a filter for active contacts or any other criteria you require. Happy customizing!
No comments:
Post a Comment