In Power Apps, lookups are often used to display data for one-to-many relationships, but the built-in filters may not always be sufficient according to the business requirement. In such cases, custom JavaScript filters can help dynamically adjust the results shown in lookup fields.

We can use the addPreSearch function available in Power Apps, it allows you to execute a custom function before the lookup field’s data is retrieved. Below is the syntax of the function –

formContext.getControl(your_control_name).addPreSearch(yourFunction)

In this, we can use the addCustomFilter function. This allows you to apply a FetchXML filter to narrow down the results shown in the lookup.

formContext.getControl(your_control_name).addCustomFilter(fetchXml, entityLogicalName)

Below is the full example which filters the contact lookup on the form to show only the users whose birthdate is before 01 Jan 2000.

JavaScript
// Get the control on the form
let contactControl = formContext.getControl("pt_contact");
contactControl.addPreSearch(filterContacts);

//...

function filterContacts() {
  // Define a custom filter
  let customContactFilter =
    `<filter type='and'>
        <condition attribute="birthdate" operator="on-or-before" value="2000-01-01"/>
      </filter>`;
      
  contactControl.addCustomFilter(customContactFilter , "contacts");
}

Using dynamic filtering in Power Apps provides better UX and ensures that users see only relevant data in lookup fields. If required you can also remove the filter by using the removePreSearch function. This ensures optimal performance and a clean user experience.