I am working on a Dynamics 365 project where I need to compare the logged-in user’s Azure AD ID with a value from a form field and display an icon based on the comparison result. My code attempts to perform this comparison but is not working as expected.
I am implementing this code in Dataverse view which has 2 columns like below
I suspect the issue is related to handling asynchronous operations.Code is added as Event Handler where ‘compareUser’ function is the starting function.
Here is my code:
function compareUser(executionContext) {
// Get Current Logged in user ID which is used to retrieve AAD id
var globalContext = Xrm.Utility.getGlobalContext();
var contextVal = globalContext.userSettings;
var loggedinUserId = contextVal.userId.replace("{", "").replace("}", "");
// Get value from field
var fieldValID = JSON.parse(executionContext).suyog_userlist_Value.id.guid;
// Pass both ids for comparison in function and return 0 or 1
var finalOutput = fetchAndCompareUserIds(loggedinUserId, fieldValID);
// Act based on returned value
switch (finalOutput) {
case 1:
console.log("User matched");
return ["suyog_testgreenicon", "Green"]; // User matched
case 0:
console.log("User doesn't match");
return ["suyog_testredicon", "Red"]; // User did not match
}
}
async function fetchAndCompareUserIds(loggedinUserId, fieldValID) {
try {
const result = await Xrm.WebApi.online.retrieveRecord("systemuser", loggedinUserId, "?$select=azureactivedirectoryobjectid");
var fetched_aad_id = result["azureactivedirectoryobjectid"];
console.log("Comparing " + fieldValID + " with " + fetched_aad_id);
if (fieldValID == fetched_aad_id) {
console.log("Match Found");
return 1;
} else {
return 0;
}
} catch (error) {
console.log(error.message);
}
}
Also, in console, when I debug, it says promise pending, unsure about this.
Thanks in Advance
My expected output should be like below if User 5 is current logged in user
1