How to hide certain fields on the User Edit form in Drupal?

raeq picture raeq · Jun 12, 2013 · Viewed 16.7k times · Source

So I have three types of users - admin, LA admin and users. I am trying to set it up so that admins and LA admins cannot edit the username, password and timezone for users. I am talking about the default user edit form for admins and the form ID is "user-profile-form".

I have created a custom module but this doesn't seem to be working. Any idea what I might be doing wrong?

Even the var_dump does not seem to be outputting. I have cleared the cache and verified that the module is enabled.

 function profile_change_form_alter(&$form, $form_state, $form_id) {
    if ($form_id === 'user-profile-form') {
       var_dump ($form);

       hide($form['account']['pass']);
       hide($form['account']['current_pass_required_values']);
       hide($form['account']['current_pass']);
    }
}

Answer

MilanG picture MilanG · Jan 10, 2014

If you use hide() you will remove the field, but hide is more for "delaying" field rendering... Like you hide it, but then (in template file) you print it at some other place. Because, if you don't print it later it won't be rendered in the page, won't be saved, if it's mandatory you'll get validation error and so on.

If you want to hide it, so user can not see it but you want the form to keep previous value of the field use something like:

$form['field_yourfield']['#access'] = FALSE;

and if you want it to be visible, but disabled (user can't change it's value) then:

$form['field_yourfield']['#disabled'] = TRUE;