Skip to main content

Notifications

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Hide /Show a button based on Security Role ( Using Ribbonworkbench ) ?

(1) ShareShare
ReportReport
Posted on by 1,401

Hello All,

I am using Following Javascript  to get  current role of User .  

How should i enable and disable a button using below  Js in Ribbon workbench .

Can anyone help me on this ?   Thank you :)

function getUerRoles()

{

var roleid = Xrm.Page.context.getUserRoles();
var name;
for (var i = 0; i < roleid.length; i++) {
var roleID = roleid[i];
var RoleName = getRoleName(roleID);
if (RoleName == 'System Administrator') {
return true;

   }
else
   {
return false;
}

}


}
function getRoleName(roleID) {


  var serverUrl = Xrm.Page.context.getClientUrl();
var OdataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleID + "'";
var roleName = null;

$.ajax({
type: "GET",
async: false,
contentType: "application/json; charset=utf-8", datatype: "json",
url: OdataURL,
beforeSend:
function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success:
function (data, textStatus, XmlHttpRequest) {
var result = data.d;
roleName = result.results[0].Name;
},
error:
function (XmlHttpRequest, textStatus, errorThrown) {
// alert('OData Select Failed: ' + odataSelect);
}
});
return roleName;

}

*This post is locked for comments

  • Suggested answer
    Ravinder Singh Jamwal Profile Picture
    65 on at
    RE: Hide /Show a button based on Security Role ( Using Ribbonworkbench ) ?

    For custom rule juts set default to "True" Instead of " False"

  • Suggested answer
    mischke Profile Picture
    10 on at
    RE: Hide /Show a button based on Security Role ( Using Ribbonworkbench ) ?

    Sadly I was unable to get the $.ajax call to work in the code above.

    So here is the code that I ended up going with.

    The request object was created via CRM REST Builder v2.6.0.0

    Found configuration within Ribbon Workbench less than straight forward, so I'll reiterate:

    Add ENABLE RULE.

    Un-customised (IsCore): False

    FunctionName: SalesOrder.shouldUserSeeButton

    Library: <path to JavaScript web resource>

    Then right click the desired ribbon button and Customise Command.
    Under the command's Enable Rules, add the newly created Enable Rule.

    Code from the JavaScript web resource:

    var SalesOrder = (function () {
        var roleMatched = false;
    
        var doesUserRoleMatch = function(roleId) {
    
            var req = new XMLHttpRequest();
            req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/roles(" + roleId + ")?$select=name", false); // false == synchronous call
            req.setRequestHeader("OData-MaxVersion", "4.0");
            req.setRequestHeader("OData-Version", "4.0");
            req.setRequestHeader("Accept", "application/json");
            req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
            req.onreadystatechange = function () {
    
                if (this.readyState === 4) {
                    req.onreadystatechange = null;
                    if (this.status === 200) {
                        var result = JSON.parse(this.response);
                        var name = result["name"];
    
                        if (name === 'System Administrator') {
                            roleMatched = true;
                        }
                        else {
                            roleMatched = false;
                        }
    
                    } else {
    					//Xrm.Utility.alertDialog('Status Text: ' + this.statusText);
                        console.log('Status Text: ' + this.statusText);
                    }
                }
            };
            req.send();
        };
        return {
            shouldUserSeeButton: function() {
    
    			//debugger;
    		
                var userRoleIds = Xrm.Page.context.getUserRoles();
        
                for (var i = 0; i < userRoleIds.length; i++) {
                    var roleId = userRoleIds[i];
    
                    doesUserRoleMatch(roleId);
        
                    if (roleMatched) {
                        return true;
                    }
                }
        
                return false;
            }
        };
    })();


  • mischke Profile Picture
    10 on at
    RE: Hide /Show a button based on Security Role ( Using Ribbonworkbench ) ?

    I've amended code and will confirm once I've verified it's working.

    function getUserRoles() {
    
        var userRoleIds = Xrm.Page.context.getUserRoles();
    
        for (var i = 0; i < userRoleIds.length; i++) {
            var roleId = userRoleIds[i];
            var roleName = getRoleName(roleId);
            if (roleName == 'System Administrator') {
                return true;
            }
        }
    
        return false;
    }
    
    function getRoleName(roleId) {
    
        var serverUrl = Xrm.Page.context.getClientUrl();
        var odataUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
        var roleName = null;
    
        $.ajax({
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8", datatype: "json",
            url: odataUrl,
            beforeSend:
                function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                },
            success:
                function (data, textStatus, XmlHttpRequest) {
                    var result = data.d;
                    roleName = result.results[0].Name;
                },
            error:
                function (XmlHttpRequest, textStatus, errorThrown) {
                    //alert('OData Select Failed: ' + odataSelect);
                }
        });
        return roleName;
    
    }
  • RugerSR762 Profile Picture
    375 on at
    RE: Hide /Show a button based on Security Role ( Using Ribbonworkbench ) ?

    I have a requirement very similar to where I need to hide the Deactivate button for all users except for users of three roles... one of which is the System Administrator.  I attempted to follow the steps outlined within this thread, confirmed repeatedly that I have done each step as described/instructed, yet either the button is hidden for everyone or it is visible to everyone.  

    I used the code below to create a JScript webresource in D365, then published it:

    // Check if the user is a system admin
    
    function getUserRoles() {
        var roleid = Xrm.Page.context.getUserRoles();
        var name;
        for (var i = 0; i < roleid.length; i++) {
            var roleID = roleid[i];
            var RoleName = getRoleName(roleID);
            if (RoleName == 'System Administrator' || RoleName == 'Sales Admin' || RoleName == 'Prog Admin') {
                return true;
            }
            else {
                return false;
            }
        }
    
    }
    function getRoleName(roleID) {
    
        var serverUrl = Xrm.Page.context.getClientUrl();
        var OdataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleID + "'";
        var roleName = null;
        $.ajax({
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8", datatype: "json",
            url: OdataURL,
            beforeSend:
            function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success:
            function (data, textStatus, XmlHttpRequest) {
                var result = data.d;
                roleName = result.results[0].Name;
            },
            error:
            function (XmlHttpRequest, textStatus, errorThrown) {
                // alert('OData Select Failed: ' + odataSelect);
            }
        });
        return roleName;
    }
    
    In Ribbon WorkBench:
    Right-clicked "Deactivate", then selected "Customise Command"

    RWB_5F00_NewRule.PNG

    In the Commands area, I selected Mscrm.HomepageGrid.Deactivate, then under Enable Rules, added a new Enable Rule:
    RWB_5F00_NewRule.PNG

    Obviously I have done something wrong or the code is bad.  Any suggestions?

  • RZP Profile Picture
    85 on at
    RE: Hide /Show a button based on Security Role ( Using Ribbonworkbench ) ?

    I am trying to Hide/Show the Qualify Lead Button based on the Security Role of the end user.  Can the above script accomplish this?  

    Thanks. 

  • Community Member Profile Picture
    on at
    RE: Hide /Show a button based on Security Role ( Using Ribbonworkbench ) ?

    here i am getting only one value in object

  • Community Member Profile Picture
    on at
    RE: Hide /Show a button based on Security Role ( Using Ribbonworkbench ) ?

    yyy.pngyyy.png

    i have given three roles but in console it is showing only sales manager 

    role = makeRequest(selectQuery);
    console.log(role);

    this i wrote to see in console

  • Community Member Profile Picture
    on at
    RE: Hide /Show a button based on Security Role ( Using Ribbonworkbench ) ?

    hello,

    see you can check opening console window click F12(Google chrome) and copy paste you code and check whether it is taking the same value you want

  • Community Member Profile Picture
    on at
    RE: Hide /Show a button based on Security Role ( Using Ribbonworkbench ) ?

    can u pls suggest the code what i have too use to get second role too if my logic is wrong

  • Community Member Profile Picture
    on at
    RE: Hide /Show a button based on Security Role ( Using Ribbonworkbench ) ?

    hi nilofer i tried to check both roles here i am just getting and alerting roles but i am getting error One of the scripts for this record has caused an error.

    TypeError: Cannot read property 'Name' of undefined at onLoad (selfemployeemi.crm8.dynamics.com/.../new_enablingButtonBasedOnroles)

      var RoleName = role[0].Name;

           var RoleName1 = role[1].Name;

           alert("Role Name1=" + RoleName1 + " Role Name=" + RoleName);

    this is what i have wrote is this correct pls correct me

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

🌸 Community Spring Festival 2025 Challenge 🌸

WIN Power Platform Community Conference 2025 tickets!

Jonas ”Jones” Melgaard – Community Spotlight

We are honored to recognize Jonas "Jones" Melgaard as our April 2025…

Kudos to the March Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 294,095 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 232,866 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,158 Moderator

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans