tags:

views:

107

answers:

1

I have a site where some users will be registered by our staff, and won't have emails associated with them. I would like to keep the email field a required field, so I devised a random email generator.

 function generateRandomEmail() {
     $email = 'noemail'. rand(0,1000000) . '@noemail.com';
     return $email;
  }

So, I attached that to the user register form alter, and it worked nicely, effectively generating an email for these users.

However, in the process, all the other fields associated with the main account section (password, username, notify, etc.) disappeared. My question, is there a quick way to populate the rest of the fields that I don't want to alter? I've used drupal_render($form); in a tpl.php, but it didn't work in the form alter.

Here is where I'm altering the form:

  function accountselect_user($op, &$edit, &$account, $category) {
    if ($op == 'register') {

       $fields['account']['mail'] = array(
       '#type' => 'textfield',
       '#default_value' => generateRandomEmail(),
    );
+2  A: 

You are currently using hook_user for your manipulation, but that is the wrong place. On $op 'registration', you can return additional fields you want to inject to the registration process, but not alter existing fields. Use hook_form_alter() or hook_form_FORM_ID_alter() for that, e.g.:

function yourModule_form_user_register_alter(&$form, &$form_state) {
  $form['account']['mail']['#default_value'] = generateRandomEmail();
}

You probably want to add a check that the request is in fact coming from the staff, since the above code would prepopulate the email field for the normal registration form also!


Also, please do not generate 'random' mail addresses using existing third party domains (like 'nomail.com'). Use the reserved 'example.com', or better yet, one that you own yourself!

Henrik Opel

related questions