Monday, June 16, 2008

Field Level Security Function

Because of a security limitation with CRM v.4.0 we had to implement an onLoad function that locked form fields based on a user's security role. To detail the issue, CRM does not allow you to restrict write access to the Account while allowing write access to related entities, mainly Opportunities and Contacts. So if you want a specific user role to be able to edit Contacts and not Accounts you have to lock the Account form using JavaScript. I found this code below on forum (sadly I didn't save the original location so if it is yours - give yourself a shout-out).

//PUT THIS CODE IN THE ONLOAD
if(UserHasRole("System Administrator"))
{
var oField1 = crmForm.all.long_taxscheduleid;
oField1.Disabled = !oField1.Disabled;
}


//THIS CODE CHECKS FOR A SPECIFIC SECURITY ROLE AND ALLOW FOR FORM EDITING
//alert(UserHasRole("System Administrator"));

function UserHasRole(roleName)
{
//get Current User Roles, oXml is an object
var oXml = GetCurrentUserRoles();

if(oXml != null)
{
//select the node text
var roles = oXml.selectNodes("//BusinessEntity/q1:name");

if(roles != null)
{

for( i = 0; i < text ="="" xml = "" version="\" encoding="\">" +
"
" +
GenerateAuthenticationHeader() +
"
" +
" " +
" " +
" role" +
"
" +
"
" +
" name" +
"
" +
"
" +
" false" +
"
" +
"
" +
" roleid" +
" role" +
" systemuserroles" +
" roleid" +
" Inner" +
"
" +
"
" +
" systemuserid" +
" systemuserroles" +
" systemuser" +
" systemuserid" +
" Inner" +
"
" +
" And" +
"
" +
"
" +
" systemuserid" +
" EqualUserId" +
"
" +
"
" +
"
" +
"
" +
"
" +
"
" +
"
" +
" " +
" " +
"
" +
"
" +
"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction"," http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");

xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var resultXml = xmlHttpRequest.responseXML;
return(resultXml);
}

No comments: