Working with Dynamics CRM users assigned roles using JavaScript
Today turned out to be one of those days where I got multiple requests for quick Dynamics CRM 2015 JavaScript help on a few projects. A colleague asked me for help showing a field on a form if a user is assigned a role and keeping it hidden otherwise. Instead of just hardcoding everything, I decided to take a more general approach and write a universal role assignment checking function that has parameters for the functions to execute if the user is or is not in the role when the role checking is called. Here it is:
//call this like CheckUserRoleAssignment("ROLE NAME", [ARRAY OF NAMES OF FUNCTIONS TO call IF TRUE], [ARRAY OF NAMES OF FUNCTION TO CALL IF FALSE]);
function CheckUserRoleAssignment(rolename, truefunctions, falsefunctions) {
SDK.REST.retrieveMultipleRecords("Role",
"$select=Name, RoleId&$filter=Name eq '"+rolename+"'",
function(data){
var userinrole = false;
if(data.length>0) {
var allroles = []
for(var i=0;i<data.length;i++){
allroles[i] = data[i].RoleId.toString();
}
var userroles = Xrm.Page.context.getUserRoles();
for(var i=0;i<userroles.length;i++){
if(allroles.indexOf(userroles[i])>-1){
userinrole = true;
}
}
}
if(userinrole){
//loop through array of "true" functions
for(var i=0;i<truefunctions.length;i++){
//call the function
truefunctions[i]();
}
}
if(!userinrole){
//loop through array of "false" functions
for(var i=0;i<falsefunctions.length;i++){
//call the function
falsefunctions[i]();
}
}
},
function(error){
//do nothing
},
function(){
//do nothing on completion
}
);
}