In the new release, Dynamics team has introduce a new method addCustomFilter. It makes it very easy to apply filters to the lookup dialog. But there is one gotcha.This method can only be called from a “PreSearch” event handler of the lookup control. This event get triggered as the user is about to view results for the lookup.
We can add and remove the event handler to the PreSearch event using addPreSearch(handler) and removePreSearch(handler) methods.
In this blog, I am going to filter the parent customer lookup on the contact entity based on the city of the contact. Here is the code.
Code
function addEventHandler() { // add the event handler for PreSearch Event Xrm.Page.getControl("parentcustomerid").addPreSearch(addFilter); } function addFilter() { //check if the city is not empty if (Xrm.Page.getAttribute("address1_city").getValue() != null) { var city = Xrm.Page.getAttribute("address1_city").getValue(); //create a filter xml var filter ="<filter type='and'>" + "<condition attribute='address1_city' operator='eq' value='" + city + "'/>" + "</filter>"; //add filter Xrm.Page.getControl("parentcustomerid").addCustomFilter(filter); } }
I am calling the addEventHandler function on the form load event.
The addEventHandler() function is used to attach the event handler to the PreSearch event of the “parentcustomerid” lookup of contact entity.
The addFilter() function will be called when the PreSearch event is triggered.
Screen Shot
In the screen shot above, the lookup is displaying accounts and contacts where city is equal to ‘Renton’
Things to remember
addCustomFilter method takes two parameters ‘filter’ and the ‘entityLogicalName’. The entityLogicalName is optional and if this parameter is provided, the filter will only apply to that entity type. Otherwise it will apply to all types of entities returned.For e.g. customer lookup control display account and contact records. If we don’t provide entityLogicalName parameter, the filter will apply to both account and contact records and if we provide “account” as a parameter then filter will only be applied to account records not to contact records.