Apply addPreSearch and addCustomFilter to a Lookup

The post describes an example of how to dynamically filter the results displayed in a model driven app lookup control using the client API addPreSearch & addCustomFilter

Scenario

A supervisor at Contoso Pharmaceuticals Limited can be added to a particular clinical trial (via the Supervisor lookup in Figure 1). This lookup control already has a filter applied to it (Figure 2); however, a second filter needs to be applied so that it’s only possible to add Supervisors listed in the Resources Pool (Figure 1)

Figure 1
Figure 2

Implementation

The JavaScript displayed below applies addPreSearch() and addCustomFilter() to the Supervisor lookup control. The filter ensures that only resources linked to the current clinical trial are displayed

function _supervisorLookupPreSearch(formContext) {
   try {
      var recordid = formContext.data.entity.getId().slice(1,-1);
      var supervisorControl = formContext.getControl("cpl_supervisorresource");
      supervisorControl.addPreSearch(function () {
          var fetchXML = "<filter type='and'><condition attribute='cpl_ctnumber' operator='eq' value='" + recordid + "'/></filter>";
          supervisorControl.addCustomFilter(fetchXML, "cpl_resource");
      });
   }
   catch (err) {
      console.error(err.message);
   }
}  

return {
   onLoad: function (executionContext) {
      var formContext = executionContext.getFormContext();
      try {
         _supervisorLookupPreSearch(formContext);
      } catch (err) {
         console.error(err.message);
      }
  },
}  

When the JavaScript is executed, the lookup filter functions correctly as illustrated in Figure 3

Figure 3

Appendix

A couple of things to note:

1.) The browser may display previously entered values (e.g. Test user2 – Supervisor) for selection in the lookup. To resolve this in the classic editor, select ‘Disable most recently used items for this field’ (Figure 4)

Figure 4

2.) If the error “0x80041103 Query Build Error” is generated (because of the link-entity in the fetch xml) when executing addCustomFilter(), then use addCustomView() instead.

Further reading

Xrm.Utility.lookupObjects to add records to a subgrid

Get and set a Dataverse lookup data type column

References

https://learn.microsoft.com/en-us/power-apps/developer/model-driven-apps/clientapi/reference/controls/addpresearch

https://learn.microsoft.com/en-us/power-apps/developer/model-driven-apps/clientapi/reference/controls/addcustomfilter