Raheel
Raheel

Reputation: 9024

Providing Default value to username field in user_register_form drupal 7

/**
 * Implements hook_form_alter()
 */
function voen_registration_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id){
    case 'user_register_form':
      $form['account']['name']['#type'] = 'hidden';
      array_unshift($form['#validate'],'_voen_registration_custom_validate');  
      array_unshift($form['#submit'],'_voen_registration_generate_username');
      break;
  }     
}

function _voen_registration_generate_username(&$form, &$form_state){
  drupal_set_message('Function Running');
}

/**
 * Since the validation functions runs before submit
 * We are assigning value to the username field so that it passes 
 * the default validation function
 */
function _voen_registration_custom_validate(&$form, &$form_state){
  $form_state['values']['name'] = 'Abc Name';
}

Hi, Thy goal i want to achieve from the above code is that i want to hide the username field from the registration form and instead i want to concatenate the first and last name to make username by code before it goes to database.

However the problem is that the default validation of the user_register_form occur before my any code. So i am trying to invoke my custom validation method before the default validation of user_register_form so that it sets the default value of username field to ABC Name.

But still now when i submit the form it shows me the error of username is required.

How can i fix this. I have to do this via code not any other module.

Upvotes: 0

Views: 260

Answers (1)

Raheel
Raheel

Reputation: 9024

Okay so i fix it by setting the #needs_validation attribute for the username field to false

$form['account']['name']['#needs_validation'] = false;

Upvotes: 0

Related Questions