Saturday, March 15, 2014

Alter username in drupal when using email registration

The username field in drupal registration form in not needed when we add our custom fields to capture user name, like First name, Last name,. . So to remove the username field from registration form i used the email_registration module. This module not only remove the username field from registration form but also gives us the feature to login using either username or email address. The problem when using email registration is, a username is generated and assigned based on the username part of the email address.
i.e., if my email id is chris@example.com, my username is set to chris. It is ok when the name is reasonable one. If the email is like iam123@example.com, the username is set to iam123 which is so annoying.

So to change the username displayed for user drupal gives us function hook_username_alter.

  1. function your_module_username_alter(&$name, $account) {
  2.     $user = user_load($account->uid);
  3.     if (!empty($user->field_first_name['und'][0]['value']) && !empty($user->
  4. field_last_name['und'][0]['value'])) {
  5.         $name = $user->field_first_name['und'][0]['value'] ." " . $user->
  6. field_last_name['und'][0]['value'];
  7.     }
  8.     else {
  9.         $name = $user->mail;
  10.     }
  11. }

No comments:

Post a Comment