How to filter Lookup Fields in CRM 2013

In CRM 2013, Microsoft introduced a new way to filter lookups. It makes it very easy to apply filters to the lookups.
A new function called “addPreSearch” has been introduced. It requires the lookup field that we want to filter and takes a filter function as a parameter. The following is an example:

function FilterContactByPhoneNumber() {
    // add the event handler to Contact Lookup and passing in PreSearch 
    // The event handler ‘filterEvent’ 

function filterEvent () {

        var telephoneNum = Xrm.Page.getAttribute("telephone1").getValue();
        //create a filter xml
        var filterXML ="<filter type='and'>" + 
                       "<condition attribute='telephone_main' operator='eq' 
                          value='" + telephoneNum + "'/>" +
      //add filter

In the FilterContactByPhoneNumber we have contactId which is the lookup that we want to filter and filterEvent that contains the filter function that is passed as an parameter to addPreSearch.
Now every time we open the lookup on the accounts form, we will hit the filterEvent function which will get the telephone1 field value on our account form and pass it as value in the filter XML, the filter XML contains attribute called telephone_main which exists on the contact entity and by passing the value from our account form we are building the filter XML , this filter XML is passed as string to the addCustomFilter, the only thing left to do is to call the FilterContactByPhoneNumber in the form on load so we can start filtering.

For more information about Microsoft CRM, click here.