simple_user_management-8.x-1.4/src/Form/UserDeleteForm.php

src/Form/UserDeleteForm.php
<?php

namespace Drupal\simple_user_management\Form;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Url;
use Drupal\role_delegation\DelegatableRolesInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * A form to delete the selected user.
 *
 * @package Drupal\simple_user_management\Form
 */
class UserDeleteForm extends FormBase {

  use MessengerTrait;

  /**
   * Constructs a UserDeactivateForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\Core\Session\AccountProxyInterface $currentUser
   *   The current user.
   * @param \Drupal\role_delegation\DelegatableRolesInterface $delegatableRoles
   *   The delegatable roles service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler
   *   The module handler service.
   */
  public function __construct(
    protected EntityTypeManagerInterface $entityTypeManager,
    protected AccountProxyInterface $currentUser,
    protected DelegatableRolesInterface $delegatableRoles,
    protected ModuleHandlerInterface $moduleHandler,
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('current_user'),
      $container->get('delegatable_roles'),
      $container->get('module_handler')
    );
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $user = FALSE) {
    $uid = $user;
    /** @var \Drupal\user\UserInterface $user */
    if ($user = $this->entityTypeManager->getStorage('user')->load($uid)) {

      // No deactivation of self.
      if ($user->id() === $this->currentUser->id()) {
        $message = $this->t('You are not allowed to delete yourself.');
        $this->messenger()->addMessage($message, 'warning');
        return $form;
      }

      // Only allow deletion if the logged in user has permission to
      // delegate all roles that the user being checked has.
      $assignable_roles = $this->delegatableRoles->getAssignableRoles($this->currentUser);
      $role_delegation_access = TRUE;
      $user_roles = $user->getRoles();
      foreach ($user_roles as $user_role) {
        if ($user_role != 'authenticated' && !in_array($user_role, array_keys($assignable_roles))) {
          $role_delegation_access = FALSE;
        }
      }

      // Allow custom control over when deletion can happen.
      $bypass_role_delegation_check = FALSE;
      $context = [
        'target_user' => $user,
        'current_user' => $this->currentUser,
      ];
      $this->moduleHandler->alter(
        'simple_user_management_delete_role_delegation_check',
        $bypass_role_delegation_check,
        $context
      );

      if ($role_delegation_access || $bypass_role_delegation_check) {
        $form['user_cancel_confirm'] = [
          '#type' => 'hidden',
          '#value' => '',
        ];
        $form['user_cancel_notify'] = [
          '#type' => 'hidden',
          '#value' => '',
        ];
        $form['uid'] = [
          '#type' => 'hidden',
          '#value' => $user->id(),
        ];
        $form['access'] = [
          '#type' => 'hidden',
          '#value' => TRUE,
        ];

        // Informational fields for the logged in user.
        $form['intro'] = [
          '#markup' => '<p>' . $this->t('Are you sure you want to deactivate the following user? This will disable the account but keep its contents.') . '</p>',
        ];
        $form['user'] = [
          '#theme' => 'item_list',
          '#items' => [],
        ];
        $form['user']['#items'][] = [
          '#markup' => $this->t('Username:') . ' ' . $user->getDisplayName(),
        ];
        $form['user']['#items'][] = [
          '#markup' => $this->t('Email:') . ' ' . $user->getEmail(),
        ];
        $form['cancel_method'] = [
          '#type' => 'fieldset',
        ];
        $form['cancel_method']['user_cancel_method'] = [
          '#type' => 'radios',
          '#required' => TRUE,
          '#options' => [
            'user_cancel_reassign' => $this->t('Delete the account and make its content belong to the Anonymous user. This action cannot be undone.'),
            'user_cancel_delete' => $this->t('Delete the account and its content. This action cannot be undone.'),
          ],
        ];

        $form['actions'] = [
          '#type' => 'container',
        ];
        $form['actions']['delete'] = [
          '#type' => 'submit',
          '#value' => $this->t('Delete'),
          '#attributes' => [
            'class' => [
              'button',
              'button--primary',
            ],
          ],
        ];
        $form['uid'] = [
          '#type' => 'hidden',
          '#value' => $uid,
        ];
      }
      else {
        $message = $this->t('You are not allowed to delete this user.');
        $this->messenger()->addMessage($message, 'warning');
      }
    }
    else {
      $message = $this->t('Unable to load the user details.');
      $this->messenger()->addMessage($message, 'warning');
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    user_cancel(
      $form_state->getValues(),
      $form_state->getValue('uid'),
      $form_state->getValue('user_cancel_method')
    );

    $form_state->setRedirectUrl(Url::fromUserInput('/admin/people'));

    // Let the admin/editor/moderator/etc know the user has been deactivated.
    $message = $this->t('The user has been successfully deleted.');
    $this->messenger()->addMessage($message, 'status');
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc