You are here

class UserMultipleCancelConfirm in Drupal 8

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

Provides a confirmation form for cancelling multiple user accounts.

@internal

Hierarchy

Expanded class hierarchy of UserMultipleCancelConfirm

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

File

core/modules/user/src/Form/UserMultipleCancelConfirm.php, line 20

Namespace

Drupal\user\Form
View source
class UserMultipleCancelConfirm extends ConfirmFormBase {
  use DeprecatedServicePropertyTrait;

  /**
   * {@inheritdoc}
   */
  protected $deprecatedProperties = [
    'entityManager' => 'entity.manager',
  ];

  /**
   * The temp store factory.
   *
   * @var \Drupal\Core\TempStore\PrivateTempStoreFactory
   */
  protected $tempStoreFactory;

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

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new UserMultipleCancelConfirm.
   *
   * @param \Drupal\Core\TempStore\PrivateTempStoreFactory $temp_store_factory
   *   The temp store factory.
   * @param \Drupal\user\UserStorageInterface $user_storage
   *   The user storage.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(PrivateTempStoreFactory $temp_store_factory, UserStorageInterface $user_storage, EntityTypeManagerInterface $entity_type_manager) {
    $this->tempStoreFactory = $temp_store_factory;
    $this->userStorage = $user_storage;
    $this->entityTypeManager = $entity_type_manager;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this
      ->t('Are you sure you want to cancel these user accounts?');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('entity.user.collection');
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this
      ->t('Cancel accounts');
  }

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

    // Retrieve the accounts to be canceled from the temp store.

    /* @var \Drupal\user\Entity\User[] $accounts */
    $accounts = $this->tempStoreFactory
      ->get('user_user_operations_cancel')
      ->get($this
      ->currentUser()
      ->id());
    if (!$accounts) {
      return $this
        ->redirect('entity.user.collection');
    }
    $root = NULL;
    $names = [];
    $form['accounts'] = [
      '#tree' => TRUE,
    ];
    foreach ($accounts as $account) {
      $uid = $account
        ->id();
      $names[$uid] = $account
        ->label();

      // Prevent user 1 from being canceled.
      if ($uid <= 1) {
        $root = intval($uid) === 1 ? $account : $root;
        continue;
      }
      $form['accounts'][$uid] = [
        '#type' => 'hidden',
        '#value' => $uid,
      ];
    }
    $form['account']['names'] = [
      '#theme' => 'item_list',
      '#items' => $names,
    ];

    // Output a notice that user 1 cannot be canceled.
    if (isset($root)) {
      $redirect = count($accounts) == 1;
      $message = $this
        ->t('The user account %name cannot be canceled.', [
        '%name' => $root
          ->label(),
      ]);
      $this
        ->messenger()
        ->addMessage($message, $redirect ? MessengerInterface::TYPE_ERROR : MessengerInterface::TYPE_WARNING);

      // If only user 1 was selected, redirect to the overview.
      if ($redirect) {
        return $this
          ->redirect('entity.user.collection');
      }
    }
    $form['operation'] = [
      '#type' => 'hidden',
      '#value' => 'cancel',
    ];

    // Display account cancellation method selection, if allowed.
    $user = $this
      ->currentUser();
    $selectCancel = $user
      ->hasPermission('administer users') || $user
      ->hasPermission('select account cancellation method');
    $form['user_cancel_method'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('When cancelling these accounts'),
      '#access' => $selectCancel,
    ];
    $form['user_cancel_method'] += user_cancel_methods();
    if (!$selectCancel) {

      // Display an item to inform the user of the setting.
      $default_method = $form['user_cancel_method']['#default_value'];
      $form['user_cancel_method_show'] = [
        '#type' => 'item',
        '#title' => $this
          ->t('When cancelling these accounts'),
        '#plain_text' => $form['user_cancel_method']['#options'][$default_method],
      ];
    }

    // Allow to send the account cancellation confirmation mail.
    $form['user_cancel_confirm'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Require email confirmation to cancel account'),
      '#default_value' => FALSE,
      '#description' => $this
        ->t('When enabled, the user must confirm the account cancellation via email.'),
    ];

    // Also allow to send account canceled notification mail, if enabled.
    $form['user_cancel_notify'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Notify user when account is canceled'),
      '#default_value' => FALSE,
      '#access' => $this
        ->config('user.settings')
        ->get('notify.status_canceled'),
      '#description' => $this
        ->t('When enabled, the user will receive an email notification after the account has been canceled.'),
    ];
    $form = parent::buildForm($form, $form_state);
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $current_user_id = $this
      ->currentUser()
      ->id();

    // Clear out the accounts from the temp store.
    $this->tempStoreFactory
      ->get('user_user_operations_cancel')
      ->delete($current_user_id);
    if ($form_state
      ->getValue('confirm')) {
      foreach ($form_state
        ->getValue('accounts') as $uid => $value) {

        // Prevent programmatic form submissions from cancelling user 1.
        if ($uid <= 1) {
          continue;
        }

        // Prevent user administrators from deleting themselves without confirmation.
        if ($uid == $current_user_id) {
          $admin_form_mock = [];
          $admin_form_state = $form_state;
          $admin_form_state
            ->unsetValue('user_cancel_confirm');

          // The $user global is not a complete user entity, so load the full
          // entity.
          $account = $this->userStorage
            ->load($uid);
          $admin_form = $this->entityTypeManager
            ->getFormObject('user', 'cancel');
          $admin_form
            ->setEntity($account);

          // Calling this directly required to init form object with $account.
          $admin_form
            ->buildForm($admin_form_mock, $admin_form_state);
          $admin_form
            ->submitForm($admin_form_mock, $admin_form_state);
        }
        else {
          user_cancel($form_state
            ->getValues(), $uid, $form_state
            ->getValue('user_cancel_method'));
        }
      }
    }
    $form_state
      ->setRedirect('entity.user.collection');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfirmFormBase::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormInterface::getCancelText 1
ConfirmFormBase::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormInterface::getDescription 11
ConfirmFormBase::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides ConfirmFormInterface::getFormName
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
DeprecatedServicePropertyTrait::__get public function Allows to access deprecated/removed properties.
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::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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
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.
UserMultipleCancelConfirm::$deprecatedProperties protected property
UserMultipleCancelConfirm::$entityTypeManager protected property The entity type manager.
UserMultipleCancelConfirm::$tempStoreFactory protected property The temp store factory.
UserMultipleCancelConfirm::$userStorage protected property The user storage.
UserMultipleCancelConfirm::buildForm public function Form constructor. Overrides ConfirmFormBase::buildForm
UserMultipleCancelConfirm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
UserMultipleCancelConfirm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
UserMultipleCancelConfirm::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormBase::getConfirmText
UserMultipleCancelConfirm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
UserMultipleCancelConfirm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
UserMultipleCancelConfirm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
UserMultipleCancelConfirm::__construct public function Constructs a new UserMultipleCancelConfirm.