2

I want to add a user to a role when a checkbox on the profile has been checked. It's printing the dpm() message but not adding the user to the role. What am I missing.

function mycustom_form_user_profile_form_alter(&$form, $form_state, $form_id) {
  $form['#validate'][] = '_user_profile_validate';
  ...
}



function _user_profile_validate(&$form, &$form_state) {
  if (($form_state['values']['field_restricted']['und'][0]['value']) == 1) {
    dpm('role added');
    global $user;
    user_multiple_role_edit(array($user->uid), 'add_role', 6);
  }
}
1
  • 1
    Did you check whether the user_multiple_role_edit() function is actually executed and all the data you're passing to it is correct?
    – Madis
    Commented May 8, 2012 at 6:50

2 Answers 2

1

Your code seems fine. Maybe you could add an additional condition to see if your role argument is proper:

$role_name = 'Role to add'; // The name of the role to add.
  if ($role = user_role_load_by_name($role_name)) {
    user_multiple_role_edit(array($user->uid), 'add_role', $role->rid);
  }

I would try adding this condition to make sure all arguments are as intended. Maybe 6 is not a valid index? With this extra condition you will be sure.

Hope this helps, cheers!

2
  • thanks. No, that id is there, I double and triple checked ;-)
    – uwe
    Commented May 8, 2012 at 5:02
  • Ah. Maybe you could step in the code with a debugger and see what gives? Commented May 8, 2012 at 5:39
1

I tried with db_insert() and got the same result. Turns out that when the profile form is saved it will overwrite the roles again, which makes sense, since Drupal thinks that the user has changed the roles on the profile form ...

So I just added the role to the form_state array and it worked:

function _user_profile_validate(&$form, &$form_state) {
  if (($form_state['values']['field_restricted']['und'][0]['value']) == 1) { 
    if (!in_array('6', $form_state['values']['roles'])){
      $form_state['values']['roles']['6'] = 6;
    }
  }
  else {
    if (in_array('restricted', $form_state['user']->roles)){
      $form_state['values']['roles']['6'] =  0;
    }
  }
}

Thanks for all the help!!!

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.