You are here

class MassPasswordResetForm in Mass Password Reset 8

Same name and namespace in other branches
  1. 2.x src/Form/MassPasswordResetForm.php \Drupal\mass_pwreset\Form\MassPasswordResetForm

Mass Password Reset Form.

Hierarchy

Expanded class hierarchy of MassPasswordResetForm

1 string reference to 'MassPasswordResetForm'
mass_pwreset.routing.yml in ./mass_pwreset.routing.yml
mass_pwreset.routing.yml

File

src/Form/MassPasswordResetForm.php, line 11

Namespace

Drupal\mass_pwreset\Form
View source
class MassPasswordResetForm extends FormBase {

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['options'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Role Options'),
      '#description' => $this
        ->t('Select all users or specific roles below.'),
      '#open' => TRUE,
    ];
    $form['options']['authenticated'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Authenticated Role'),
      '#description' => $this
        ->t('Selecting Authenticated will reset all users.'),
      '#open' => TRUE,
    ];
    $form['options']['authenticated']['authenticated_role'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Select all users'),
      '#required' => FALSE,
    ];
    $form['options']['custom_roles'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Roles'),
      '#open' => TRUE,
    ];
    $form['options']['custom_roles']['selected_roles'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Select Roles to Reset'),
      '#options' => mass_pwreset_get_custom_roles(),
      '#required' => FALSE,
      '#states' => [
        'disabled' => [
          ':input[name="authenticated_role"]' => array(
            'checked' => TRUE,
          ),
        ],
      ],
    ];
    $form['notify'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Notify Users'),
      '#open' => TRUE,
    ];
    $form['notify']['notify_active_users'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Notify active users of password reset via email'),
      '#default_value' => 0,
    ];
    $form['notify']['notify_blocked_users'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Notify blocked users of password reset via email'),
      '#default_value' => 0,
      '#states' => [
        'visible' => [
          ':input[name="notify_active_users"]' => array(
            'checked' => TRUE,
          ),
        ],
      ],
    ];
    $form['admin'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Administrator Reset'),
      '#description' => $this
        ->t('Include the administrative superuser id 1 account in the list of passwords being reset.'),
      '#open' => FALSE,
    ];
    $form['admin']['include_admin_user'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Include admin user (uid1)'),
      '#default_value' => 0,
    ];

    // Resetting your own password causes an error at the end of the batch.
    $form['current_user_note'] = [
      '#type' => 'item',
      '#markup' => $this
        ->t('The user submitting this form will not be included in the password reset batch.'),
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['reset_passwords'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Reset Passwords'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // Get the selected roles from the form.
    $selected_roles = array_filter($form_state
      ->getValue('selected_roles'));

    // User must select roles for mass password reset.
    if ($form_state
      ->getValue('authenticated_role') == 0 && empty($selected_roles)) {
      $form_state
        ->setErrorByName('authenticated_role', $this
        ->t('Please select all users or select specific roles.'));
      return;
    }

    // Holds all the user ids to have the passwords reset.
    $uids = [];

    // If reset for all users is checked, get all the uids - excluding the
    // current user id and user 1.
    if ($form_state
      ->getValue('authenticated_role') == 1) {
      $uids = mass_pwreset_get_uids();
      $roles = [
        'authenticated role',
      ];
    }
    else {
      $roles = $selected_roles;
      $uids = mass_pwreset_get_uids_by_selected_roles($roles);
    }

    // If there are no users returned and there are roles selected, set error.
    if (empty($uids) && $selected_roles) {
      $form_state
        ->setErrorByName('selected_roles', $this
        ->t('There are no users with the selected role.'));
    }

    // Set the 'uids' and 'roles' values for use in submitForm.
    $form_state
      ->set('uids', $uids);
    $form_state
      ->set('roles', $roles);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Get 'uids' and 'roles' values set in form validation.
    $uids = $form_state
      ->get('uids');
    $roles = $form_state
      ->get('roles');

    // If the admin user is to be included in the reset and the current user is
    // NOT the super admin user, add the uid of 1 to the $uids array.
    // A check to see if the current user is 1 is required because resetting
    // your own password will make the batch fail.
    if ($form_state
      ->getValue('include_admin_user') == 1 && $this
      ->currentUser()
      ->id() != 1) {
      array_push($uids, 1);
    }

    // Construct the batch data array that will be used in the batch process.
    $batch_data = [
      'uids' => $uids,
      'notify_active_users' => $form_state
        ->getValue('notify_active_users'),
      'notify_blocked_users' => $form_state
        ->getValue('notify_blocked_users'),
      'roles' => $roles,
    ];

    // Store batch data in private tempstore.
    $tempstore = \Drupal::service('tempstore.private')
      ->get('mass_pwreset');
    $tempstore
      ->set('batch_data', $batch_data);

    // Redirect to the confirm form.
    $form_state
      ->setRedirect('mass_pwreset_confirm_form');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
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. 1
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. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
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 Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MassPasswordResetForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
MassPasswordResetForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MassPasswordResetForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MassPasswordResetForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
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. 1
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 Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.