Conditionally assign a custom role on user registration 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']-&gt;roles[] = 'customRole';


A var_dump($form) gives:

    ["#user"]=&gt;
  object(stdClass)#111 (4) {
    ["uid"]=&gt;
    int(0)
    ["hostname"]=&gt;
    string(14) "myhost"
    ["roles"]=&gt;
    array(2) {
      [1]=&gt;
      string(14) "anonymous user"
      [2]=&gt;
      string(9) "customRole"
    }
    ["cache"]=&gt;
    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.
You need to use hook_user_presave. like below,

function mymodule_user_presave(&amp;$edit, $account, $category) {
  if ($account-&gt;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.