Filtered lookup view in Dynamics CRM 2011 using JavaScript

Zhen Yuwang, 17 April 2012

In Dynamics CRM 2011, we can set up a lookup view by editing Filter Criteria which could have several conditions. Those conditions could be based on fields, related entity’s fields and even related entity’s related entity’s fields. However, this is still not enough in some situations. We need a few dynamic customer views which can smartly show records based on previous users’ selection in other fields on form.

Please consider this scenario: we have a form with 2 fields, Job lookup and Product lookup. 

  Filtered lookup view in Dynamics CRM 2011 using JavaScript

After uses select a specific Job, the Product lookup field should ONLY show those Product records which are in Job Product of this Job. This is not supported by default filtered lookup in the form customization area, because we need to filter Product by 1 user-specified Job record.

So, firstly, we need get the GUID of job entity,

 Filtered lookup view in Dynamics CRM 2011 using JavaScript

Then set some parameters,

 Filtered lookup view in Dynamics CRM 2011 using JavaScript

The “viewId” just need to be a valid GUID. Any GUID is fine. The “entityName” should be the name of entity which this custom view belongs to.

Next is getting the fetchXML. It should be the hardest part; however Dynamics CRM 2011 has already done for us. 

Go to Advance Find and make a find like this

 Filtered lookup view in Dynamics CRM 2011 using JavaScript

Download Fetch XML, change the attributes we want, replace the id in condition with previous JobId, and replace the double quote with single quote.

Finally, we get Fetch XML:

 Filtered lookup view in Dynamics CRM 2011 using JavaScript

The last parameter is layoutXml and it is also simple:

 Filtered lookup view in Dynamics CRM 2011 using JavaScript

Add this line of code to our JavaScript.
 Filtered lookup view in Dynamics CRM 2011 using JavaScript

Save and publish our JavaScript. Let’s see how it works.

 Filtered lookup view in Dynamics CRM 2011 using JavaScript

 Filtered lookup view in Dynamics CRM 2011 using JavaScript

So, the customer lookup field filters Products. It only shows Products in Job Product of selected Job.