Here is an example of the code needed in Microsoft Dynamics CRM 2015 to return the roles for the current user.
function onLoad() { // ** Shows all the roles for current user var Roles = Xrm.Page.context.getUserRoles(); for (var i = 0; i < Roles.length; i++) { var RoleId = Roles[i]; var selectQuery = "/RoleSet?$top=1&$filter=RoleId eq guid'" + RoleId + "'&$select=Name"; var role = null; role = makeRequest(selectQuery); var RoleName = role[0].Name; alert("Role ID=" + RoleId + " Role Name=" + RoleName); } }
function makeRequest(query) { var serverUrl = Xrm.Page.context.getClientUrl(); var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/"; oDataEndpointUrl += query; var service = GetRequestObject(); if (service != null) { service.open("GET", oDataEndpointUrl, false); service.setRequestHeader("X-Requested-With", "XMLHttpRequest"); service.setRequestHeader("Accept", "application/json, text/javascript, */*"); service.send(null); var retrieved = JSON.parse(service.responseText).d; var results = new Array(); for (var i = 0; i < retrieved.results.length; i++) { results.push(retrieved.results[i]); } return results; } return null; }
function GetRequestObject() { if (window.XMLHttpRequest) { return new window.XMLHttpRequest; } else { try { return new ActiveXObject("MSXML2.XMLHTTP.3.0"); } catch (ex) { return null; } } }
Thanks so much Neil – there is a huge swathe of JavaScript for CRM out there, much of it dated and still using deprecated methods. I spent a day trying various solutions but this version, which was subtly different to the rest, worked first time, and for CRM 2016 too – much appreciated. Why there isn’t a command to do this built into the xrm model I will never understand..
LikeLike
Pingback: CRM2016 JavaScript – Context Object | Microsoft Dynamics CRM and Unified Service Desk
Pingback: CRM2016 JavaScript – Context Object - Microsoft Dynamics CRM Community
Just to update in V9.0 now the Xrm.Page API has got deprecated. So one must use following API to get user roles:
var context = Xrm.Utility.getGlobalContext();
var roleIds = context.userSettings.securityRoles;
LikeLike
Thanks Khadim, my post is old now and you are right we should now use the context.
LikeLike