Last active
February 24, 2021 01:07
-
-
Save johannez/161f8f488368c41f1d92aeb2245ece7f to your computer and use it in GitHub Desktop.
Drupal 8 - Allow login by email
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could this code be integrated into the Drupal core? Or why doesn't Drupal implement login via email?