Hi, Team
I am using Dynamics 365 CRM online V9.0. I am trying to add a custom filter on a lookup filed.
Since MS recommended us to use Xrm.WebApi. so we’re changing all our services to use Xrm.WebApi.
Below is my code:
var Sdk = window.Sdk || {}; (function() { // Define some global variables var myUniqueId = "_myUniqueId"; // Define an ID for the notification var currentUserName = Xrm.Utility.getGlobalContext().userSettings.userName; // get current user name var message = currentUserName + ": Your JavaScript code in action!"; this.addUnitLookupFilter = function(formContext) { try { var lookup_Values = ''; Xrm.WebApi.retrieveMultipleRecords("account", "?$select=name&$filter=startswith(name,'A')").then( function(results) { for (var i = 0; i < results.entities.length; i++) { var field_value = results.entities[i]["name"]; lookup_Values = lookup_Values + "<value>" + field_value + "</value>"; } console.log(results); if (lookup_Values != '') { var fetchXml = '<filter type="and">' + '<condition attribute="name" operator="in">' + lookup_Values + '</condition>' + '</filter>'; formContext.getControl("parentaccountid").addCustomFilter(fetchXml); console.log(fetchXml); } }, function(error) { console.log("addUnitLookupFilter--err"); } ); } catch (err) { console.log(err); } console.log("addUnitLookupFilter--end"); } // Code to run in the form OnLoad event this.filterUnitLookupOnFormLoad = function(executionContext) { var formContext = executionContext.getFormContext(); // display the form level notification as an INFO formContext.ui.setFormNotification(message, "INFO", myUniqueId); // Wait for 5 seconds before clearing the notification window.setTimeout(function() { formContext.ui.clearFormNotification(myUniqueId); }, 50000); var parentControl = formContext.getControl("parentaccountid"); console.log(parentControl.getName()); parentControl.addPreSearch(function() { Sdk.addUnitLookupFilter(formContext); }); } }).call(Sdk);
in the code, I use Xrm.WebApi to retrieve data and then add it to the custom filter.
But it does not work well. I use F12 to trace the log. It shows that Xrm.WebApi is an Async call. The function will first return false before the Xrm.WebApi request completed.
Do you have any suggestions? I tried to use the following methods to refresh but failed.
formContext.data.refresh(true); formContext.ui.refreshRibbon(true);
Thanks