User registration logic per role

By berliner, 27 November, 2013

The project I'm currently working on requires different registration paths and logic for users with different roles. The heavy lifting of having different paths for the registration page, different form elements to collect profile data, and also the final role assignment is done with the Profile2 Registration Path module. Very nice work of grasmash (he has a nice blog too btw).

But one piece was missing. I needed to allow users who where finally getting only the authenticated role to register without admin approval, but other users with a specific role shouldn't have that right. There is no permission for that, no setting, and a standard drupal system allows for only one type of registration. No module out there that promised a quick solution. So I started looking into user_register_submit() to see how I could hook into there. While digging through that function I realized that the solution is a lot easier than I had expected.

My setup is the following: I have normal customers (authenticated role) and artists (authenticated role and artist role). The former should register without approval, the later with approval.
To achieve this it was sufficient to register my own submit handler to run before the user_register_submit() and then change one single form value.

First the submit handler:

function mymodule_form_user_register_form_alter(&$form, $form_state) {
  array_unshift($form['#submit'], 'mymodule_user_register_form_submit');

Second the manipulation of the status value:

 * Custom submit handler for the user registration form.
 * This is used to differentiate account register settings for normal
 * authenticated users vs. artist:
 * authenticated users: Do not need admin approval.
 * artists: Need admin approval.
function mymodule_user_register_form_submit($form, &$form_state) {
  $roles = array_filter($form_state['values']['roles']);
  if (count($roles) == 1) {
    // This is a normal user account.
    $form_state['values']['status'] = 1;
  else {
    // This is an artist account.
    $form_state['values']['status'] = 0;

$form_state['values']['status'] controls whether the registering user will be activated immediately or only later after admin approval. This effectively differentiates the both cases I needed to implement. Luckily this also controls which welcome emails will be send out, so that there is no confusion for the user.