2

I need to override the 'user/%user/edit' page for a specific user role, say 'foo_role'. I have successfully created the new user registration form that explicitly selects the fields to be used in creating a new foo_role user however, because there are additional user fields not applicable to foo_role the edit page for this role is not correct.

This is my best attempt, but it fails:

function registermodule_form_user_profile_form_alter($form, &$form_state){
        global $user;
        if(in_array("foo_role", $user->roles)){
            unset($form['field_non_foo']);
        }   
        return $form;
 }
jpstrikesback
  • 2,300
  • 14
  • 18
luckyape
  • 722
  • 8
  • 22

2 Answers2

4

Alter hooks use variable reference to modify variable contents in memory. Because of that, you also don't need to return a value in alter hooks.

Should look like this:

function registermodule_form_user_profile_form_alter(&$form, &$form_state){
  global $user;

  if(in_array("foo_role", $user->roles)){
    $form['field_non_foo'] = FALSE;
  }   
}
mattacular
  • 1,849
  • 13
  • 17
  • Shouldn't this be the answer? luckape is missing the '&' before his function $form variable... – emc May 10 '12 at 18:57
3

Can you clarify "fails"?

First, you are missing the & from $form. Change that for a start.

If that doesn't fix it, try to figure out how much of your code is actually working. Try adding a drupal_set_message('user is in foo role'); inside the if condition.

If that shows, then it is a problem with the unset. Note that you shouldn't use unset but instead set '#access' to FALSE. Like this:

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

You could even go fancy and directly save whatever is returned from in_array_check():

$form['field_non_foo']['#access'] = in_array('foo_role', $user->roles);

There is however a difference here and that is that #access will now be forced to be either TRUE or FALSE and not use whatever value it might already have.

Edit: Are you sure that your field isn't inside a fieldset? Then it would be $form['the_fieldset']['field_non_foo'] instead.

Berdir
  • 6,881
  • 2
  • 26
  • 38
  • Berdir, props for proofing me - it was indeed the missing reference & on the argument. The unset else was showing the expected results in the dpm() - made things perplexing - thanks for you help. q - why not unset? – luckyape Feb 16 '11 at 20:46
  • Maybe another module expects that the file exists. unsetting it actually means that it is completely gone. setting access to false will simply hide and use the default value – Berdir Feb 16 '11 at 20:53