PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites: Login using email and username in Drupal 7

15 Apr 2016

Login using email and username in Drupal 7

   This blog describes about how to login using both email and username in Drupal 7. All of you know we could login using only username in Drupal 7.

Login using mail address and usename in Drupal 7


       I've tried to login using email without any contrib modules. Finally i got the code. First alter form to add custom form validation. In custom form validation, get the name from user table by email and set that value into name field in form.  Let see the code:

<?php
/**
 * Implement hook_form_alter().
 */
function phponwebsites_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == "user_login" || $form_id == "user_login_block") {
    $form['name']['#title'] = t('Username or E-mail Address');
    // Ensure a valid validate array.
    $form['#validate'] = is_array($form['#validate']) ? $form['#validate'] : array();
    // login using username or email address
    array_unshift($form['#validate'],'phponwebsites_user_login_validate');
  }
}

 /**
 * Implement phponwebsites_user_login_validate()
 *
 * Return name by its email address
 */
function phponwebsites_user_login_validate($form, &$form_state) {
  if (isset($form_state['values']['name']) && strpos($form_state['values']['name'], '@') !== false) {
      $name = db_query("SELECT name FROM {users} WHERE LOWER(mail) = LOWER(:name)", array(':name' => $form_state['values']['name']))->fetchField();
    }
  if (isset($name)) {
    form_set_value($form['name'], $name, $form_state);
  }
}

   Now you can login using both username and email. I've hope you know how to login using both username and email in Drupal 7.

4 comments:

  1. Or you could use a more standard approach like https://www.drupal.org/project/email_registration or https://www.drupal.org/project/logintoboggan which are both widely used and adopted.

    ReplyDelete
  2. Also, the Super Login module accomplishes this in a lightweight way without the bloat of the logintoboggan module: https://www.drupal.org/project/super_login

    ReplyDelete
  3. The least expensive approach to set up and consistently manufacture an enrollment site is to make a direct mail advertisement.
    TalkTalk login/

    ReplyDelete
  4. The developer has moved a module that meets your need from the sandbox to the project page:
    https://www.drupal.org/project/login_email

    The module exists as 7.x-1.x-dev It works as is...looks like a bit of assistance can turn this into an official release.

    Email Registration changes the registration process and Login Toboggan is pretty heavy.

    ReplyDelete