0

I've written a custom module that uses hook_form_alter() to set some default values from GET-parameters when the user registration form is called with certain GET values. That is, if you call mysite.com/user/register?firstname=Derp you'll find that the form field "Firstname" is magically filled with "Derp".

Now here it comes: When a specific GET value is given, then and only then I'd like to automatically assign an existing custom role to the new user. That's not to be achieved with Rules and the like. (Yes, I know that anyone with even small insight in programming may exploit this to get the role, but the role is not really important).

I've tried to update the register form values with:

$form['#user']->roles[] = 'customRole';

A var_dump($form) gives:

    ["#user"]=>
  object(stdClass)#111 (4) {
    ["uid"]=>
    int(0)
    ["hostname"]=>
    string(14) "myhost"
    ["roles"]=>
    array(2) {
      [1]=>
      string(14) "anonymous user"
      [2]=>
      string(9) "customRole"
    }
    ["cache"]=>
    int(0)
  }

...but it seems that this data gets sorted out during the processing of the form. Thus the role is not assigned.

Alternatively I could assign the role directly using user_multiple_role_edit(), but I need the uid for that, which in turn is assigned during user_register_submit(). That function however seems to be beyond the reach of any API function I've found so far.

I'd be glad to read about your thoughts how I could assign the role on registration (to say it again: Rules doesn't do the job). Thank you.

1 Answer 1

0

You need to use hook_user_presave. like below,

function mymodule_user_presave(&$edit, $account, $category) {
  if ($account->is_new) {
    $roles = user_roles(TRUE);
    $rid = array_search('Test', $roles);
    if ($rid != FALSE) {
      $edit['roles'][$rid] = 1;
    }
  }
}

Replace the Test with your role name. $account->is_new will be set to 1 during the registration process alone, so your code will not execute when a user updates the profile.

2
  • Works perfect. Thank you, Mathankumar. You don't know by chance how to do this with Drupal 6?
    – MiBerG
    Commented Jul 15, 2013 at 13:48
  • 1
    Nevermind, I found out how to do this in D6: mymodule_user('insert', &$edit, &$user, $category = NULL){ //do something }
    – MiBerG
    Commented Jul 15, 2013 at 14:14

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.