Skip to content

Instantly share code, notes, and snippets.

@johannez
Last active February 24, 2021 01:07
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save johannez/161f8f488368c41f1d92aeb2245ece7f to your computer and use it in GitHub Desktop.
Save johannez/161f8f488368c41f1d92aeb2245ece7f to your computer and use it in GitHub Desktop.
Drupal 8 - Allow login by email
<?php
/**
* Implements hook_form_alter().
*/
function MODULE_form_user_login_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
// Allow login with email.
array_unshift($form['#validate'], 'MODULE_user_login_form_validate');
// Change the field label.
$form['name']['#title'] = new \Drupal\Core\StringTranslation\TranslatableMarkup('Email or Username');
}
/**
* Callback to check for a valid email for login.
*/
function MODULE_user_login_form_validate(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
if (!$form_state->isValueEmpty('name') && \Drupal::service('email.validator')->isValid($form_state->getValue('name'))) {
// Try to find a user name for this email.
if ($user = user_load_by_mail($form_state->getValue('name'))) {
$form_state->setValue('name', $user->getUsername());
}
}
}
@VishalKumarSahu
Copy link

Could this code be integrated into the Drupal core? Or why doesn't Drupal implement login via email?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment