-2

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?

2
  • 1
    Other than do it with Form API and hook_form_alter?
    – Kevin
    May 18, 2023 at 14:32
  • can you show me an example?
    – MrSnrub
    May 19, 2023 at 0:16

1 Answer 1

0
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.