class UserPasswordForm in Drupal 8
Same name and namespace in other branches
- 9 core/modules/user/src/Form/UserPasswordForm.php \Drupal\user\Form\UserPasswordForm
 - 10 core/modules/user/src/Form/UserPasswordForm.php \Drupal\user\Form\UserPasswordForm
 
Provides a user password reset form.
Send the user an email to reset their password.
@internal
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\user\Form\UserPasswordForm
 
 
Expanded class hierarchy of UserPasswordForm
1 file declares its use of UserPasswordForm
- UserPasswordFormTest.php in core/
modules/ user/ tests/ src/ Kernel/ Form/ UserPasswordFormTest.php  
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 22  
Namespace
Drupal\user\FormView source
class UserPasswordForm extends FormBase {
  /**
   * The user storage.
   *
   * @var \Drupal\user\UserStorageInterface
   */
  protected $userStorage;
  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;
  /**
   * The flood service.
   *
   * @var \Drupal\Core\Flood\FloodInterface
   */
  protected $flood;
  /**
   * Constructs a UserPasswordForm object.
   *
   * @param \Drupal\user\UserStorageInterface $user_storage
   *   The user storage.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\Core\Config\ConfigFactory $config_factory
   *   The config factory.
   * @param \Drupal\Core\Flood\FloodInterface $flood
   *   The flood service.
   */
  public function __construct(UserStorageInterface $user_storage, LanguageManagerInterface $language_manager, ConfigFactory $config_factory = NULL, FloodInterface $flood = NULL) {
    $this->userStorage = $user_storage;
    $this->languageManager = $language_manager;
    if (!$config_factory) {
      @trigger_error('Calling ' . __METHOD__ . ' without the $config_factory is deprecated in drupal:8.8.0 and is required before drupal:9.0.0. See https://www.drupal.org/node/1681832', E_USER_DEPRECATED);
      $config_factory = \Drupal::configFactory();
    }
    $this->configFactory = $config_factory;
    if (!$flood) {
      @trigger_error('Calling ' . __METHOD__ . ' without the $flood parameter is deprecated in drupal:8.8.0 and is required before drupal:9.0.0. See https://www.drupal.org/node/1681832', E_USER_DEPRECATED);
      $flood = \Drupal::service('flood');
    }
    $this->flood = $flood;
  }
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager')
      ->getStorage('user'), $container
      ->get('language_manager'), $container
      ->get('config.factory'), $container
      ->get('flood'));
  }
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'user_pass';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Username or email address'),
      '#size' => 60,
      '#maxlength' => max(UserInterface::USERNAME_MAX_LENGTH, Email::EMAIL_MAX_LENGTH),
      '#required' => TRUE,
      '#attributes' => [
        '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'] = [
        '#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.', [
          '%email' => $user
            ->getEmail(),
        ]),
        '#suffix' => '</p>',
      ];
    }
    else {
      $form['mail'] = [
        '#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'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
    ];
    $form['#cache']['contexts'][] = 'url.query_args';
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $flood_config = $this->configFactory
      ->get('user.flood');
    if (!$this->flood
      ->isAllowed('user.password_request_ip', $flood_config
      ->get('ip_limit'), $flood_config
      ->get('ip_window'))) {
      $form_state
        ->setErrorByName('name', $this
        ->t('Too many password recovery requests from your IP address. It is temporarily blocked. Try again later or contact the site administrator.'));
      return;
    }
    $this->flood
      ->register('user.password_request_ip', $flood_config
      ->get('ip_window'));
    $name = trim($form_state
      ->getValue('name'));
    // Try to load by email.
    $users = $this->userStorage
      ->loadByProperties([
      'mail' => $name,
    ]);
    if (empty($users)) {
      // No success, try to load by name.
      $users = $this->userStorage
        ->loadByProperties([
        '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.', [
          '%name' => $name,
        ]));
      }
      else {
        // Register flood events based on the uid only, so they apply for any
        // IP address. This allows them to be cleared on successful reset (from
        // any IP).
        $identifier = $account
          ->id();
        if (!$this->flood
          ->isAllowed('user.password_request_user', $flood_config
          ->get('user_limit'), $flood_config
          ->get('user_window'), $identifier)) {
          $form_state
            ->setErrorByName('name', $this
            ->t('Too many password recovery requests for this account. It is temporarily blocked. Try again later or contact the site administrator.'));
          return;
        }
        $this->flood
          ->register('user.password_request_user', $flood_config
          ->get('user_window'), $identifier);
        $form_state
          ->setValueForElement([
          '#parents' => [
            'account',
          ],
        ], $account);
      }
    }
    else {
      $form_state
        ->setErrorByName('name', $this
        ->t('%name is not recognized as a username or an email address.', [
        '%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.', [
        '%name' => $account
          ->getAccountName(),
        '%email' => $account
          ->getEmail(),
      ]);
      $this
        ->messenger()
        ->addStatus($this
        ->t('Further instructions have been sent to your email address.'));
    }
    $form_state
      ->setRedirect('user.page');
  }
}Members
| 
            Name | 
                  Modifiers | Type | Description | Overrides | 
|---|---|---|---|---|
| 
            DependencySerializationTrait:: | 
                  protected | property | An array of entity type IDs keyed by the property name of their storages. | |
| 
            DependencySerializationTrait:: | 
                  protected | property | An array of service IDs keyed by property name used for serialization. | |
| 
            DependencySerializationTrait:: | 
                  public | function | 1 | |
| 
            DependencySerializationTrait:: | 
                  public | function | 2 | |
| 
            FormBase:: | 
                  protected | property | The config factory. | 1 | 
| 
            FormBase:: | 
                  protected | property | The request stack. | 1 | 
| 
            FormBase:: | 
                  protected | property | The route match. | |
| 
            FormBase:: | 
                  protected | function | Retrieves a configuration object. | |
| 
            FormBase:: | 
                  protected | function | Gets the config factory for this form. | 1 | 
| 
            FormBase:: | 
                  private | function | Returns the service container. | |
| 
            FormBase:: | 
                  protected | function | Gets the current user. | |
| 
            FormBase:: | 
                  protected | function | Gets the request object. | |
| 
            FormBase:: | 
                  protected | function | Gets the route match. | |
| 
            FormBase:: | 
                  protected | function | Gets the logger for a specific channel. | |
| 
            FormBase:: | 
                  protected | function | 
            Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: | 
                  |
| 
            FormBase:: | 
                  public | function | Resets the configuration factory. | |
| 
            FormBase:: | 
                  public | function | Sets the config factory for this form. | |
| 
            FormBase:: | 
                  public | function | Sets the request stack object to use. | |
| 
            LinkGeneratorTrait:: | 
                  protected | property | The link generator. | 1 | 
| 
            LinkGeneratorTrait:: | 
                  protected | function | Returns the link generator. | |
| 
            LinkGeneratorTrait:: | 
                  protected | function | Renders a link to a route given a route name and its parameters. | |
| 
            LinkGeneratorTrait:: | 
                  public | function | Sets the link generator service. | |
| 
            LoggerChannelTrait:: | 
                  protected | property | The logger channel factory service. | |
| 
            LoggerChannelTrait:: | 
                  protected | function | Gets the logger for a specific channel. | |
| 
            LoggerChannelTrait:: | 
                  public | function | Injects the logger channel factory. | |
| 
            MessengerTrait:: | 
                  protected | property | The messenger. | 29 | 
| 
            MessengerTrait:: | 
                  public | function | Gets the messenger. | 29 | 
| 
            MessengerTrait:: | 
                  public | function | Sets the messenger. | |
| 
            RedirectDestinationTrait:: | 
                  protected | property | The redirect destination service. | 1 | 
| 
            RedirectDestinationTrait:: | 
                  protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
| 
            RedirectDestinationTrait:: | 
                  protected | function | Returns the redirect destination service. | |
| 
            RedirectDestinationTrait:: | 
                  public | function | Sets the redirect destination service. | |
| 
            StringTranslationTrait:: | 
                  protected | property | The string translation service. | 1 | 
| 
            StringTranslationTrait:: | 
                  protected | function | Formats a string containing a count of items. | |
| 
            StringTranslationTrait:: | 
                  protected | function | Returns the number of plurals supported by a given language. | |
| 
            StringTranslationTrait:: | 
                  protected | function | Gets the string translation service. | |
| 
            StringTranslationTrait:: | 
                  public | function | Sets the string translation service to use. | 2 | 
| 
            StringTranslationTrait:: | 
                  protected | function | Translates a string to the current language or to a given language. | |
| 
            UrlGeneratorTrait:: | 
                  protected | property | The url generator. | |
| 
            UrlGeneratorTrait:: | 
                  protected | function | Returns the URL generator service. | |
| 
            UrlGeneratorTrait:: | 
                  public | function | Sets the URL generator service. | |
| 
            UrlGeneratorTrait:: | 
                  protected | function | Generates a URL or path for a specific route based on the given parameters. | |
| 
            UserPasswordForm:: | 
                  protected | property | The flood service. | |
| 
            UserPasswordForm:: | 
                  protected | property | The language manager. | |
| 
            UserPasswordForm:: | 
                  protected | property | The user storage. | |
| 
            UserPasswordForm:: | 
                  public | function | 
            Form constructor. Overrides FormInterface:: | 
                  |
| 
            UserPasswordForm:: | 
                  public static | function | 
            Instantiates a new instance of this class. Overrides FormBase:: | 
                  |
| 
            UserPasswordForm:: | 
                  public | function | 
            Returns a unique string identifying the form. Overrides FormInterface:: | 
                  |
| 
            UserPasswordForm:: | 
                  public | function | 
            Form submission handler. Overrides FormInterface:: | 
                  |
| 
            UserPasswordForm:: | 
                  public | function | 
            Form validation handler. Overrides FormBase:: | 
                  |
| 
            UserPasswordForm:: | 
                  public | function | Constructs a UserPasswordForm object. |