FILTER LOOKUP IN DYNAMICS 365 BASED ON CONDITION IN JAVASCRIPT WITH ADDCUSTOMFILTER AND ADDPRESEARCH
Working with lookups provide you many possibilities regarding filtering the records displayed in the lookup.
You can do it by using the out of the box related records filtering in the lookup field properties, however and in some scenarios, this approach
does not provide what you need.
Therefore, writing JavaScript code is mandatory to achieve what you want, which is the topic of this post
In other post, we saw
how to filter lookup field in JavaScript using the function addCustomView
In this post, we will see how to filter a lookup field in JavaScript using addPreSearch and addCustomFilter functions.
For the sake of this post, we will filter the Parent Account lookup in the account form based on the category field
- We have to create a fetch Xml, where we are going to use the filter part only and not the whole fetch Xml
- In our example, we will use the account category as the condition to filter the list of available accounts in the parent account lookup
-
Call the below function on form load and use the addPreSearch that takes a function as a parameter where the filter is done using addCustomFilter
function applyParentAccountPreSearch(context) {
var formContext = context.getFormContext();
formContext.getControl("parentaccountid").addPreSearch(applyParentAccountFilter);
}
-
Below is the function where the addCustomFilter is used to filter the lookup based on the condition you set
function applyParentAccountFilter(context) {
var formContext = context.getFormContext();
var filter = '<filter type="and">';
filter += '<condition attribute="accountcategorycode" operator="eq" value="2" />';
filter += '</filter>';
formContext.getControl("parentaccountid").addCustomFilter(filter);
}
-
You can now go to an account record and click to select a record from the Parent Account lookup,
you will notice that the accounts are now filtered based on the condition you have added
- In the above example, we put the condition as a static value but of course you can do it to be dynamically set based on your needs
- Another optional parameter can be passed to the addCustomFilter function which the entity that the view will look up to
- The new filter will be added to the default filter already applied of the lookup view with the AND operator
- In case you didn't use the filter element, you will get the following error "Invalid Child Node, valid nodes are filter, order, link-entity, attribute, all-attributes, no-attrs"
Hope This Helps!
Comments
Post a Comment