I am using an editable grid in Dynamics 365 sales. In this editable grid the fields that are of interest are the optionset field and Lookup field. Lookup value(reference record) has a text field 'market', my motive is to filter the lookup values tied to the specific market when a certain optionset value is selected, else show all lookup values. I performed this successfully in the main form but facing problem implementing the same logic in the editable grid. Looking forward for your suggestions. Thanks. Below is my Js code
function filterProdRightsForTerrOnSubgrid(executionContext) {
var formContext = executionContext.getFormContext();
var eventSource = executionContext.getEventSource();
var gridContext = formContext.getControl("OpportunityProductsGrid");
var optionSetValue, lookupControl;
// Check if the context is a subgrid row
if (eventSource) {
// Get the option set field value
var optionSetValue = gridContext.getAttribute("optionsetfield").getValue();
// Get the lookup control
var lookupControl = gridContext.getControl("lookupfield").getControlType();
// Ensure the lookup control exists
if (lookupControl == null) {
console.error("Lookup control not found.");
return;
}
// Clear any existing filters
lookupControl.removePreSearch(function () {
addLookupFilter(executionContext);
});
// Check if option set field has a value that requires filtering
if (optionSetValue === 802050018 || optionSetValue === 802050240 || optionSetValue === 802050091) {
lookupControl.addPreSearch(function () {
addLookupFilter(executionContext);
});
}
else {
// No filter is applied when the option set value differs
lookupControl.removePreSearch(function () {
addLookupFilter(executionContext); // This ensures no filter is applied
});
console.log("No option set value or different value selected, showing all lookup values.");
}
}
}
function addLookupFilter(executionContext) {
var formContext = executionContext.getFormContext();
var gridContext = formContext.getControl("OpportunityProductsGrid");
// Get the lookup field control
var lookupControl = gridContext.getControl("lookupfield").getControlType();
// Get the option set field value
var optionSetValue = formContext.getAttribute("optionsetfield").getValue();
if (optionSetValue === 802050018 || optionSetValue === 802050240 || optionSetValue === 802050091) {
// FetchXML to filter the lookup values based on the 'market' field
var fetchXML = "<filter type='and'>" +
"<condition attribute='market' operator='eq' value='DACH' />" + // Change 'DACH' as needed
"</filter>";
lookupControl.addCustomFilter(fetchXML, "lookupEntity");
}
else {
// Apply an empty filter to show all records (no actual filtering)
var emptyFilter = "<filter type='and'></filter>";
lookupControl.addCustomFilter(emptyFilter, "lookupEntity");
}
}