You are here

class UserPasswordForm in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/user/src/Form/UserPasswordForm.php \Drupal\user\Form\UserPasswordForm

Provides a user password reset form.

Hierarchy

Expanded class hierarchy of UserPasswordForm

1 string reference to 'UserPasswordForm'
user.routing.yml in core/modules/user/user.routing.yml
core/modules/user/user.routing.yml

File

core/modules/user/src/Form/UserPasswordForm.php, line 20
Contains \Drupal\user\Form\UserPasswordForm.

Namespace

Drupal\user\Form
View source
class UserPasswordForm extends FormBase {

  /**
   * The user storage.
   *
   * @var \Drupal\user\UserStorageInterface
   */
  protected $userStorage;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * Constructs a UserPasswordForm object.
   *
   * @param \Drupal\user\UserStorageInterface $user_storage
   *   The user storage.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   */
  public function __construct(UserStorageInterface $user_storage, LanguageManagerInterface $language_manager) {
    $this->userStorage = $user_storage;
    $this->languageManager = $language_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity.manager')
      ->getStorage('user'), $container
      ->get('language_manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'user_pass';
  }

  /**
   * {@inheritdoc}
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Username or email address'),
      '#size' => 60,
      '#maxlength' => max(USERNAME_MAX_LENGTH, Email::EMAIL_MAX_LENGTH),
      '#required' => TRUE,
      '#attributes' => array(
        'autocorrect' => 'off',
        'autocapitalize' => 'off',
        'spellcheck' => 'false',
        'autofocus' => 'autofocus',
      ),
    );

    // Allow logged in users to request this also.
    $user = $this
      ->currentUser();
    if ($user
      ->isAuthenticated()) {
      $form['name']['#type'] = 'value';
      $form['name']['#value'] = $user
        ->getEmail();
      $form['mail'] = array(
        '#prefix' => '<p>',
        '#markup' => $this
          ->t('Password reset instructions will be mailed to %email. You must log out to use the password reset link in the email.', array(
          '%email' => $user
            ->getEmail(),
        )),
        '#suffix' => '</p>',
      );
    }
    else {
      $form['mail'] = array(
        '#prefix' => '<p>',
        '#markup' => $this
          ->t('Password reset instructions will be sent to your registered email address.'),
        '#suffix' => '</p>',
      );
      $form['name']['#default_value'] = $this
        ->getRequest()->query
        ->get('name');
    }
    $form['actions'] = array(
      '#type' => 'actions',
    );
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $name = trim($form_state
      ->getValue('name'));

    // Try to load by email.
    $users = $this->userStorage
      ->loadByProperties(array(
      'mail' => $name,
    ));
    if (empty($users)) {

      // No success, try to load by name.
      $users = $this->userStorage
        ->loadByProperties(array(
        'name' => $name,
      ));
    }
    $account = reset($users);
    if ($account && $account
      ->id()) {

      // Blocked accounts cannot request a new password.
      if (!$account
        ->isActive()) {
        $form_state
          ->setErrorByName('name', $this
          ->t('%name is blocked or has not been activated yet.', array(
          '%name' => $name,
        )));
      }
      else {
        $form_state
          ->setValueForElement(array(
          '#parents' => array(
            'account',
          ),
        ), $account);
      }
    }
    else {
      $form_state
        ->setErrorByName('name', $this
        ->t('%name is not recognized as a username or an email address.', array(
        '%name' => $name,
      )));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $langcode = $this->languageManager
      ->getCurrentLanguage()
      ->getId();
    $account = $form_state
      ->getValue('account');

    // Mail one time login URL and instructions using current language.
    $mail = _user_mail_notify('password_reset', $account, $langcode);
    if (!empty($mail)) {
      $this
        ->logger('user')
        ->notice('Password reset instructions mailed to %name at %email.', array(
        '%name' => $account
          ->getUsername(),
        '%email' => $account
          ->getEmail(),
      ));
      drupal_set_message($this
        ->t('Further instructions have been sent to your email address.'));
    }
    $form_state
      ->setRedirect('user.page');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
FormBase::$loggerFactory protected property The logger factory.
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator protected function Returns the link generator.
LinkGeneratorTrait::l protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator public function Sets the link generator service.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service.
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service.
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator protected function Returns the URL generator service.
UrlGeneratorTrait::redirect protected function Returns a redirect response object for the specified route.
UrlGeneratorTrait::setUrlGenerator public function Sets the URL generator service.
UrlGeneratorTrait::url protected function Generates a URL or path for a specific route based on the given parameters.
UserPasswordForm::$languageManager protected property The language manager.
UserPasswordForm::$userStorage protected property The user storage.
UserPasswordForm::buildForm public function Overrides FormInterface::buildForm
UserPasswordForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
UserPasswordForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
UserPasswordForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
UserPasswordForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
UserPasswordForm::__construct public function Constructs a UserPasswordForm object.