I have a custom user email field, I want when the user signs up to automatically set the email for he/she.

For example, when the username field is user1 I want set the email to user1@mydomain.com and save it in email field.

How can I do this?


If you'd like to customize the user registration form, you're probably looking at a custom module to take care of this; an invocation of hook_form_alter() can step in and alter the behavior of the user registration form. For example, adding the following functions to MYMODULE:

 * Implements hook_form_alter().
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  // Disable the email field
  $form['account']['mail']['#access'] = FALSE;

  // @TODO: Override validation functions in $form['#validate'] 
  // that check the mail field

  // Replace the user registration form submission with
  // the function MYMODULE_form_user_register_form_submit 
  $form['#submit'] = array('MYMODULE_form_user_register_form_submit');

// Alter the disabled mail field before 
// submitting registration form to user_register_submit()
function MYMODULE_form_user_register_form_submit($form_id, &$form_state) {
  // add '@mydomain.com' to the submitted username field
  $form_state['values']['mail'] = $form_state['values']['name'] .  '@mydomain.com';
  user_register_submit($form_id, $form_state);

This only get you partially there, as overriding such key functionality requires many scenarios to validate now that a key assumption is gone (e.g. what happens when someone enters an email for a name, what happens when a user needs to recover password, etc.).

It might be helpful to look at the source code of the Optional mail on register module to see how that is accomplished so you can under how modules can override Drupal's user registration functionality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy