Today I am going to tell you how to do filter lookup field using JavaScript.
Here you need to do two things:
- Get the filtered data in the form of fetchXML as per the your requirement.
- You will need to create a custom look view. (You are going to click 'View more records,' if you dont have it will throw an error so you need to create custom lookup view)
So here...
- My requirement is On Entity Custom3 I have two fields,
lookup field Custome1 (lookup to Custome1 entity) and lookup field Custome2 (lookup to Custome2 entity).
Lookup field Custome1 should get filtered by lookup field Custome2.
(Entity Custome1 is having N:1 relationship with Entity Custome2)
I have code ready we can use it:
- getFetchXMLData: function(entityLogicalName, attibute, attributeValue)
- {
-
-
-
-
-
-
-
-
-
-
-
-
-
- var condition = null;
- if (attibute != null || attributeValue != null) condition = " <filter type='and'> " +
- " <condition attribute='" + attibute + "' operator='eq' value='" + attributeValue + "' /> " +
- " </filter> "
- var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' >" +
- "<entity name='" + entityLogicalName + "' >" + condition +
- "</entity>" +
- "</fetch>"
- return fetchXml;
- }
- Now the second step: We have filtered data and we need to create a custom lookup view.
I have code ready that can be used here:
- createCustomLookupView: function(columnsForCustomLookup, entityLogicalName, fieldName, viewDisplayName, fetchXml)
- {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var columns = "";
- for (var i = 0; i < columnsForCustomLookup.length; i++)
- {
- columns += "<cell name='" + columnsForCustomLookup[i] + "' width='150' />";
- }
- var layoutXml = "<grid name='resultset' object='1' select='1' icon='1' preview='1'>" +
- "<row name='result' id='" + entityLogicalName + "id'>" + columns +
- "</row>" +
- "</grid>";
-
- var viewId = "{00000000-0000-0000-0000-000000000001}";
- Xrm.Page.getControl(fieldName).addCustomView(viewId, entityLogicalName, viewDisplayName, fetchXml, layoutXml, true);
- }
Now on change event of lookup Custome2 field I can call the methods:
- onCustome2Change: function(context)
- {
- var guidOfCustome2;
- var lookup = Xrm.Page.data.entity.attributes.get(Custome2);
- if (lookup != null)
- {
- var lookUpObjectValue = lookup.getValue();
- if ((lookUpObjectValue != null))
- {
- guidOfA = lookUpObjectValue[0].id;
- }
- }
- if (guidOfA == null) return;
- var fetchXML = getFetchXMLData(logicalNameOfCustom1, Custome2, guidOfCustome2)
-
- createCustomLookupView([name, phone], logicalNameOfCustom1, Custome1, " Custom Lookup View Name", fetchXml);
- }
Hope this will help you to get your work done.
If you have any issues with the code, please comment below and suggestions are welcomed.