Filtering Lookup view based on custom logic CRM 2011
In one of my requirement, I have to filter my lookup view results based on another lookup field value.
I have 2 Lookup fields on my form
- Product
- Product Category
When I click on “Product” lookup, I have to show only Products with category as “Product Category” field value.
We can achieve this requirement using Jscript by following below steps
- Create a new view with our filter
- Use the SDK method addCustomView, to add newly created view for the lookup dialog box
- Set this view as default view
- Disable the view selector to avoid user to select other views from Lookup dialog
- Put above logic in a function register it on “onchange” event of “Product Category” field
Below is the Jscript function
function createAndSetLookupView() {
// Some GUID but only needs to be unique among the other available views for the lookup
var viewId = “{CB6F8184-D7C2-4664-9FAB-18FD9DCDB22A}”;
// Name of the view
var viewDisplayName = “My filtered view”;
// Prepare the xml with columns to display and filter
// Tip : Use Advanced Find to prepare th FetchXML
var fetchXml = “<fetch version=’1.0′ ” +
“output-format=’xml-platform’ ” +
“mapping=’logical’>” +
“<entity name=’new_product’>” +
“<attribute name=’new_productid’ />” +
“<attribute name=’new_name’ />” +
“<attribute name=’new_categoryid’ />” +
“<attribute name=’createdon’ />” +
“<order attribute=’new_name’ ” +
“descending=’false’ />” +
“<filter type=’and’>” +
“<condition attribute=’new_categoryid’ ” +
“operator=’eq’ ” +
“uiname='” + {categoryName} + “‘ ” +
“uitype=’new_category’ ” +
“value='” + {categoryGUID} + “‘ />” +
“</filter>” +
“</entity>” +
“</fetch>”;
var layoutXml = “<grid name=’resultset’ ” +
“object=’1′ ” +
“jump=’new_name’ ” +
“select=’1′ ” +
“icon=’1′ ” +
“preview=’2′>” +
“<row name=’result’ ” +
“id=’new_productid’>” +
“<cell name=’new_name’ ” +
“width=’150′ />” +
“<cell name=’new_categoryid’ ” +
“width=’150′ />” +
“<cell name=’createdon’ ” +
“width=’100′ />” +
“</row>” +
“</grid>”;
try {
// Lookup field which you want to add new view
var lookupControl = Xrm.Page.ui.controls.get(“new_productid”);
// Add the created view to Product lookup and set this view as default
lookupControl.addCustomView(viewId, “new_product”, viewDisplayName, fetchXml, layoutXml, true);
//Disable “View Selection” dropdown of “Product” lookup dialog
document.getElementById(“new_productid”).setAttribute(“disableViewPicker”, “1”);
}
catch (e) {
alert(“Error in createAndSetLookupView() – ” + e.description);
}
}
🙂
Can I use this code to filter a partylist field instaed of a lookup? Please let me know ASAP.
I tried it but it gives me errors when the window with the views pops up.