Dynamics 365 Education and Knowledge

Dynamics 365 Education and Knowledge

https://charlesabikhirs.blogspot.com

FILTER LOOKUP IN DYNAMICS 365 BASED ON CONDITION IN JAVASCRIPT WITH ADDCUSTOMFILTER AND ADDPRESEARCH

Published

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
  1. We have to create a fetch Xml, where we are going to use the filter part only and not the whole fetch Xml
  2. In our example, we will use the account category as the condition to filter the list of available accounts in the parent account lookup
  3. 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);
    }


  4. 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);
    }


  5. 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
    Lookup prefilter 1

    Lookup prefilter 2

  6. 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
  7. Another optional parameter can be passed to the addCustomFilter function which the entity that the view will look up to
  8. The new filter will be added to the default filter already applied of the lookup view with the AND operator
  9. 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!

Continue to website...

More from Dynamics 365 Education and Knowledge