How to create custom lookup view using JavaScript in D365/MSCRM?

Spread the Knowledge...

Custom Lookup View in Dynamics 365

Sometime there is a requirement to show the filtered records in the lookup field. 

In this blog, we will learn how to create a custom lookup view in Dynamics 365 with filtered records using JavaScript.

Custom lookup view is used to gather all the filtered data using FetchXML and show it in lookup field of the entity. However, there is no such default functionality available to achieve this requirement.

So we have to write a simple javascript code which will set the filtered records in the lookup field.

Check the below example of custom lookup view.

function newCustomLookupMethod() {
var entityName = "account";
var viewDisplayName = "GetActiveAccounts";

//Get the value of ObjectTypeCode of an entity based on its logical name
var objTypeCode = Mscrm.EntityPropUtil.EntityTypeName2CodeMap[entityName];

//Dummy GUID for CustomLookupView.
var viewId = "{B9E5AC5B-D709-47AA-B82A-061B84E90C0B}";

//Query to fetch filtered records.
var fetchXml = "<!--?xml version='1.0'?>" +
"<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>" +
"<entity name='workflow'> <attribute name='name'/>" +
"<attribute name='modifiedon'/>" +
"<attribute name='createdon'/>" +
"<filter type='and'>" +
"<condition attribute='primaryentity' operator='eq' value='" + objTypeCode + "' />" +
"</filter> " +
"<filter type='and'>" +
"<condition attribute='statecode' operator='eq' value='1' />" +
"</filter>" +
"</entity> " +

//Create layout for custom view.
var layoutXml = "<grid name='resultset' " +
"object='1' " +
"jump='workflowid' " +
"select='1' " +
"icon='1' " +
"preview='1'>" +
"<row name='result' " +
"id='workflowid'>" +
"<cell name='name'/>" +
"width='100' />" +
"<cell name='statuscode'/>" +
"width='100' />" +
"<cell name='modifiedon'/>" +
"width='100' />" +
"</row>" +

var lookup = Xrm.Page.getControl("schemaname of the Lookupcontrol");
lookup.addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);

Hope this helps to resolve the issue.


Happy CRMing!!!

Spread the Knowledge...