Product: Dynamics 365 CE, Model Driven Apps Language: JavaScript
Doing an operation based on the logged-in user’s security roles is a common requirement is any Dynamics / PowerApps implementation. Here is a simple code, that you can re-use to do any activity based on user’s role.
For this example, I have taken a scenario of hiding / showing a tab in a form based on specific roles.
function showTabsByRole(executionContext)
{
// Function to hide the appointments tab by role
"use strict";
var formContext = executionContext.getFormContext();
var roleCollection;
var rolesVisibleFor = ["System Customiser", "System Administrator"]; // Replace this with the role you need
var shouldBeVisible = false;
var userSettings = Xrm.Utility.getGlobalContext().userSettings;
if (userSettings.roles._collection != null)
{
roleCollection = userSettings.roles._collection;
}
else return;
Object.values(roleCollection).forEach(function (obj)
{
rolesVisibleFor.forEach(function (item)
{
if (obj.name == item)
{
shouldBeVisible = true;
formContext.ui.tabs.get("appointmentstab").setVisible(shouldBeVisible);
return;
}
});
});
formContext.ui.tabs.get("appointmentstab").setVisible(shouldBeVisible);
}