Javascript – Return Roles

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;
		}
	}
}

5 thoughts on “Javascript – Return Roles

  1. 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..

    Like

  2. Pingback: CRM2016 JavaScript – Context Object | Microsoft Dynamics CRM and Unified Service Desk

  3. Pingback: CRM2016 JavaScript – Context Object - Microsoft Dynamics CRM Community

  4. 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;

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s