I'm using Drupal 7 and I have a standard text field in my Content Type. If the user with role "Standard User" is adding a new node then they should be able to set the Status field text value. However, if the node is already created and they are editing/updating that same node, it should be grayed-out (disabled). Is there a way to do this?
1 Answer
function my_module_form_node_form_alter(&$form, &$form_state, $form_id) {
$node = $form_state['node'];
if ($form_id == "my_content_type_node_form") {
global $user;
if (isset($user)) {
$user_has_standard_user_role = FALSE;
// Get role information about the user.
$user_roles = array();
foreach ($user->roles as $key => $role) {
$user_roles[$key] = $role;
}
foreach ($user_roles as $key => $user_role) {
if ($user_role == "Standard User") {
$user_has_standard_user_role = TRUE;
}
} // end iterate through user roles
if ($user_has_standard_user_role) {
// If this is a new node, let the user edit the field.
if (!isset($node->nid) || isset($node->is_new)) {
$form['field_status_field']['und']['#disabled'] = FALSE;
}
// If this is not a new node, then disable the field.
else {
$form['field_status_field']['und']['#disabled'] = TRUE;
}
} // end if user has Standard User role.
// User is not Standard User, so disable the field.
else {
$form['field_status_field']['und']['#disabled'] = TRUE;
}
} // end if user is set
} // end if correct form ID
} // end function