Filter Dynamics CRM Lookup Values with Javascript

Author by Dan Fink

Dynamcis CRM added some new features in 2013 realted 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,

function preFilterLookup()
{
Xrm.Page.getControl("new_State").addPreSearch(function () { 

var stateObject = Xrm.Page.getAttribute("new_State").getValue();

// Get the lookup Object, and extract the Value (ID and Text)
if(stateObject != null)
{
var stateTextValue = stateObject[0].name;
var stateID = stateObject[0].id;

// Filter the cities by State
fetchXml = "";

// Apply the filter to the field
Xrm.Page.getControl("new_City").addCustomFilter(fetchXml);
}

});
}
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.
Author

Dan Fink

Senior System Engineer