Even though CRM has a newer feature of filtering lookups on CRM forms by using “.addCustomFilter” together with the “.preFilterSearch”  on the control of a lookup attribute, its fetchXML consists of opening and closing <filter> tags around the condition statement. So what does this mean? Why aren’t we able to use this newer feature, instead of reaching out for process of creating custom View in the code which is a little more complex. With fetchXML with only filter part I wasn’t able to perform some more complex filter for lookup. For example, what if we want to include linked entity filter into condition on fetchXML , in this case there is a need for writing entire fetchXML statement as we see it inside SavedQuery (View) entity records. The only way to use this whole statement is to filter lookup by using addCustomView.

blogaddcustomview

You can use the Advanced Find to get the fetchXML query that includes custom filter with link-entity filter. Instead of this I’ve created System View with this fetchXML and queried the data on SavedQuery entity to retrieve fetchXML together with layoutXML statement.

While creating new Contact record,  on Primary Account lookup field we want to filter records so there can be only visible records of account with country set to “United States’, thereat this value is saved inside Address entity with relationship to Account entity. Below is how the lookup Primary Account looks before the applied filter.

blog3
To filter this we use the following code on load the form and apply “.addCustomView” on lookup control.
blogpostCode

On this image we can see records of addresses, where first to records are the records where country is set to “United States”.

blogpost4

After applying the filter, these are lookup records available while searching the matching.

blog4

There are some other requirements that needs to be settled in order to get the desired behavior.  In Additional Properties section of lookup field, we need to select default view, and choose the view we created and got the fetchXML from this same view. In Our example this will be:

Default View – Filtered Accounts,

View Selector – Show Selected Views (if we choose Off, there will not the be the possibility to select the Custom View)

Get the view Id from default view and apply it to custom View filter. Then we would get the following if we select ‘Look Up More Records’ option.

blogpost3