Bhubaneswar, Odisha, India
+91-8328865778
support@softchief.com

Show/Hide Command Button depending on current user security Role Code Snippet without network call request

Show/Hide Command Button depending on current user security Role Code Snippet without network call request

Here is a code snippet by which you can show/hide command buttons by checking Current user Security Role in background or Async way. This way it is now free to interact with the page while the request is performing background job getting data.  No more freezing of the user interface while the page is loading!

// NOTE: Don't do this code as it calls server to get data!
function userHasRole(roleName) {
    const roleIds = Xrm.Utility.getGlobalContext().userSettings.securityRoles;
    let hasRole = false;
    roleIds.forEach(function(roleId) {
        const request = new XMLHttpRequest();

        // Pass false for the async argument to force synchronous request
        request.open('GET', '/api/data/v9.2/roles(' + roleId + ')', false);
        request.send(null);
        if (request.status === 200) {
            const result = JSON.parse(request.responseText);
            if (result.name === roleName) {
                hasRole = true;
            }
        }
    });

    return hasRole;
}

The below code checks if the current user having a specif role without any extra network calls and performs async call.

//use this code
function userHasRole(roleName) {
    const matchingRoles = Xrm.Utility.getGlobalContext().userSettings.roles.get(function(role) {
        return role.name === roleName;
    });
    return matchingRoles.length > 0;
}

Hope it helps.