web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Show/Hide the subgrid Based on the User Role

(0) ShareShare
ReportReport
Posted on by

Hello Everyone, I got the requirement for java script to Hide/Show sub grid Based on the User Role , I wrote the code but somehow it is not working as expected , So please can someone help me where i went wrong , I am using Dynamics CRM 2013 

Sample Code:

// function to hide the section Based on the UserRoles
function OnLoad() {

if (UserHasRole("System Administrator") || UserHasRole("Sales Effectiveness")) {
Xrm.Page.ui.tabs.get("TAB").sections.get("Section1").setVisible(true);
Xrm.Page.ui.tabs.get("TAB").sections.get("Section2").setVisible(true);

} else {
Xrm.Page.ui.tabs.get("TAB").sections.get("Section1").setVisible(false);
Xrm.Page.ui.tabs.get("TAB").sections.get("Section2").setVisible(false);

}
}


function UserHasRole(roleName) {
var serverUrl = Xrm.Page.context.getServerUrl();
var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";

oDataEndpointUrl += "RoleSet?$top=1&$filter=Name eq '" + roleName + "'";

var service = GetRequestObject();

if (service != null) {
service.open("GET", oDataEndpointUrl, false);
service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json, text/javascript, */*");
service.send(null);

var requestResults = eval('(' + service.responseText + ')').d;

if (requestResults != null && requestResults.results.length == 1) {
var role = requestResults.results[0];

var id = role.RoleId;

var currentUserRoles = Xrm.Page.context.getUserRoles();

for (var i = 0; i < currentUserRoles.length; i++) {
var userRole = currentUserRoles[i];
if (GuidsAreEqual(userRole, id)) {
return true;
}
}
}
}

return false;
}

function GetRequestObject() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
} else {
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
} catch (ex) {
return null;
}
}
}

function GuidsAreEqual(guid1, guid2) {
var isEqual = false;

if (guid1 == null || guid2 == null) {
isEqual = false;
} else {
isEqual = guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase();
}

return isEqual;
}

*This post is locked for comments

I have the same question (0)
  • Arun Vinoth Profile Picture
    11,615 Moderator on at

    Any errors? Did you debug?

  • Mahendar Pal Profile Picture
    45,095 on at

    Hi Ramesh,

    Try to debug your code and check if you are getting your server URL correctly if not try to use getClientUrl  instead of getServerUrl

  • Suggested answer
    Community Member Profile Picture
    on at

    What is not working?  A few questions: 

    • is the role being returned correctly for the user?
    • Are the helper functions working correctly? (i.e. GuidsAreEqual)
    • Are you seeing errors when attempting to Hide/Show the sections?
    • do you have any other required fields in the sections?  In CRM 2011, I saw some strange behavior in hiding a section when the Owner field was in the section.

    I do see a possible issue with the UserHasRole method. Does it always return false? I believe that synchronous Xml HTTP requests have been deprecated in recent versions of most browsers. So the async == false is ignored and you immediately return.

    I would suggest something similar to the following snippet created using the CRM Rest Builder:

    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/roles?$filter=( name eq 'System%20Administrator' or  name eq 'Sales%20Effectiveness')", true);
    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 results = JSON.parse(this.response);
                for (var i = 0; i < results.value.length; i++) {
                    var roleid = results.value[i]["roleid"];
    
                    // DO THE HIDE/SHOW WORK HERE
                    // OR INVOKE ANOTHER METHOD
                }
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();

    Let me know if this helps fix the issue!

    jim 

  • Suggested answer
    gdas Profile Picture
    50,091 Moderator on at

    Try with this -

            function OnLoad() {
                if (UserHasRole("System Administrator") || UserHasRole("Sales Effectiveness")) {
                    Xrm.Page.ui.tabs.get("TAB").sections.get("Section1").setVisible(true);
                    Xrm.Page.ui.tabs.get("TAB").sections.get("Section2").setVisible(true);
    
                } else {
                    Xrm.Page.ui.tabs.get("TAB").sections.get("Section1").setVisible(false);
                    Xrm.Page.ui.tabs.get("TAB").sections.get("Section2").setVisible(false);
                }
            }
    
    
    
            function UserHasRole(RoleName) {
                var currentUserRoles = Xrm.Page.context.getUserRoles();
                for (var i = 0; i < currentUserRoles.length; i++) {
                    var userRoleId = currentUserRoles[i];
                    var userRoleName = GetRoleName(userRoleId);
                    if (userRoleName == RoleName) {
                        return true;
                    }
                }
                return false;
            }
    
            function GetRoleName(roleId) {
                var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
                var odataSelect = 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: odataSelect,
                        beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
                        success: function (data, textStatus, XmlHttpRequest) {
                            roleName = data.d.results[0].Name;
                        },
                        error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect); }
                    }
                                );
                return roleName;
            }


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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans