Insights Filter Dynamics CRM Lookup Values with Javascrip

Filter Dynamics CRM Lookup Values with Javascrip

Dynamcis CRM added some new features in 2013 related to filtering lookups which have been covered by others in the past, however, in the event you want to filter a lookup value based on another lookup, rather than a string value, there is some additional code required. There are quite a few instances where you might want to filter lookups based on another lookup, so I’ve d To give an example of where this might be used, let’s assume you have two custom entites called State and City. Both of these entities are populated with records for all the states in the US, and the largest cities within those states. All of the City records have a field called State, where you can set the state that city resides in. (Note that this could be done better with parental relationships, etc. but for this example, let’s assume it was not done this way). In practice this would look like a form with a State lookup and a City lookup. This would work, but the city lookup is going to show every available city, and once a State is selected, we would much prefer the available records in the City lookup to be those which have their State field set to the State we just selected. The documented method mentioned earlier allows you to filter the lookup, but only based on a string. Since we want to read another lookup field rather than a string, we’re going to get an error using that code, as it’s expecting a GUID for the string and is receiving an Object instead. If you try to run that code, you’ll get an error like this:  An exception System.FormatException was thrown while trying to convert input value ‘[object Object]’ to attribute ”. Expected type of attribute value: System.Guid. To accomplish this, we’ll need to write some JavaScript which runs on the State field and filters the City lookup records based on the record selected in the State lookup. To do this, add the following JavaScript to a Library, and add an Event Handler OnChange to the State field,

Essentially what we’re doing here is first taking the State object from the lookup field, making sure it has a value, then setting two new variables for the Name and ID of the object. These two values can then be passed into the fetchXML which is used in the addCustomFilter function to filter down the lookup to only records which have the same State as you just selected.