Harinder Maan
Harinder Maan

Reputation: 61

hook_form_alter to unset fields according to a user's role

I am facing a problem when I try to use hook_form_alter to hide fields according to user's roles. I have used unset() and removed the field from the $form array, but it is still showing when the form is rendered.

Here is my code:

function mymodule_form_alter($form, $form_state, $form_id){
  global $user;
  if($form_id == 'my_content_type'){
    if(array_key_exists(5,$user->roles) && !array_key_exists(3,$user->roles)){
      if(empty($form_state['field']['args'][0]->title)){
        unset($form['field_body']);
      }
    }
  }
}

Upvotes: 5

Views: 1534

Answers (3)

hexasoft
hexasoft

Reputation: 677

It exists a module which allows to hide fields. For Drupal 9 it handles per-roles, hide-or-disable, exceptions (such as not at creation…). Look at: https://www.drupal.org/project/jammer

Upvotes: 0

Harinder Maan
Harinder Maan

Reputation: 61

I have found the solution. I need just added the & with $form and $form_state in hook_form_alter parameters. Like hook_form_alter(&$form, &$form_state, $form_id)

Upvotes: 0

norman.lol
norman.lol

Reputation: 5374

Instead of using unset() to hide a form element, you should set the #access property to FALSE. This keeps the form build tree intact, which avoids problems if other modules try to access or alter that information. Source

function MYMODULE_form_alter($form, $form_state, $form_id) {

  global $user;
  $account = $user;

  if ($form_id == 'MYCONTENTTYPE_node_form') {

    if (user_has_role(5, $account) && !user_has_role(3, $account)) {

      if (empty($form_state['field']['args'][0]->title)) {

        $form['field_body']['#access'] = FALSE;
      }
    }
  }
}

If this is still not working, double-check your if-requests. Are they really doing something? Are you currently logged-in as a corresponding user?

Upvotes: 3

Related Questions