Dynamics 365 is a powerful customer relationship management (CRM) tool that allows businesses to manage their data and relationships effectively. One common requirement in CRM customization is the ability to filter lookup fields based on the values of another field, particularly when dealing with Option Set fields. In this blog post, we will explore how to achieve this using JavaScript.
I have an entity called "Organisation" in Dynamics 365, and it has two fields:
1. Relationship type with Linked Organisation (Option Set).
2. Linked Organisation (Lookup).
Based on “Relationship type with Linked Organisation” field (Option Set) I want to filter “Linked Organisation” field (Lookup).
Now, let's write the JavaScript code to filter the "Linked Organisation" (lookup) field based on the "Relationship type with Linked Organisation" (Option Set) field.
Explanation of above code:
Relationship_With_Linked_Organisation: This stores the schema name of the Option Set field.
Linked_Organisation: This stores the schema name of the Lookup field.
orgType: This stores the value of Option set field i.e., “Relationship With Linked Organisation” field value.
formContext.getControl(Linked_Organisation).addPreSearch(...): This event handler will execute a function just before the lookup dialog is displayed.
addLookupFilter: This function filters the lookup field.
addPreSearch: Executes just before a lookup field's search dialog is opened.
In the fetchXML use only filter part of the XML query, you need to select the field which has the same value as “Relationship type with Linked Organisation” field so that with the same values record can be filtered.
Publish the above code in a Web resource and call the function “filterLookup” on “OnLoad” event and “OnChange” event of the “Relationship type with Linked Organisation” field.
Organisation Type field will be selected in the filter xml.
As we can see below “Linked Organisation” lookup field is filtered based on “Relationship type with Linked Organisation” field.
In conclusion, this blog post demonstrates how to leverage JavaScript within Dynamics 365 CRM to dynamically filter lookup fields based on the values of Option Set fields, enhancing the customization capabilities of the CRM system. This feature is particularly valuable when you need to streamline data entry and ensure data integrity by guiding users to select related records more effectively.