- 
								
																
																
									Dynamically Disable Fields Based on Security Roles
									JavaScript
									Disable Fields Based on Security Roles: Use JavaScript to disable or hide fields based on the user's security role, enforcing field-level security on the client side.
								 
							 	
						
						
						Disable Fields Based on Security Roles: Use JavaScript to disable or hide fields based on the user's security role, enforcing field-level security on the client side.
// Disable Fields Based on Security Roles security on the client side.
function disableFieldsForRoles(executionContext) {
    const userRoles = Xrm.Utility.getGlobalContext().userSettings.roles;
    const restrictedRoles = ["GUID_of_role_1", "GUID_of_role_2"];
    const formContext = executionContext.getFormContext();
    if (userRoles.some(role => restrictedRoles.includes(role.id))) {
        formContext.getControl("restrictedField").setDisabled(true);
    }
}
Now let's suppose you don't have the GUIDs of the security roles, but only the names, you can proceed as described below : 
// Code description
function disableFieldsForRoles(executionContext) {
    // List of restricted role names
    const restrictedRolesNames = ["Role Name 1", "Role Name 2"];
    // Get the form context
    const formContext = executionContext.getFormContext();
    // Get the roles of the current user
    const userRoles = Xrm.Utility.getGlobalContext().userSettings.roles;
    // Check if the user has a restricted role
    userRoles.forEach(function (role) {
        Xrm.WebApi.retrieveRecord("role", role.id).then(function (result) {
            if (restrictedRolesNames.includes(result.name)) {
                // Disable the field if the role is restricted
                formContext.getControl("restrictedField").setDisabled(true);
            }
        }).catch(function (error) {
            console.error("Error retrieving role:", error);
        });
    });
}