class DeleteMultipleForm

Same name in other branches
  1. 8.9.x core/lib/Drupal/Core/Entity/Form/DeleteMultipleForm.php \Drupal\Core\Entity\Form\DeleteMultipleForm
  2. 10 core/lib/Drupal/Core/Entity/Form/DeleteMultipleForm.php \Drupal\Core\Entity\Form\DeleteMultipleForm
  3. 11.x core/lib/Drupal/Core/Entity/Form/DeleteMultipleForm.php \Drupal\Core\Entity\Form\DeleteMultipleForm

Provides an entities deletion confirmation form.

Hierarchy

Expanded class hierarchy of DeleteMultipleForm

2 files declare their use of DeleteMultipleForm
ConfirmDeleteMultiple.php in core/modules/comment/src/Form/ConfirmDeleteMultiple.php
DeleteMultiple.php in core/modules/node/src/Form/DeleteMultiple.php

File

core/lib/Drupal/Core/Entity/Form/DeleteMultipleForm.php, line 20

Namespace

Drupal\Core\Entity\Form
View source
class DeleteMultipleForm extends ConfirmFormBase implements BaseFormIdInterface {
    
    /**
     * The current user.
     *
     * @var \Drupal\Core\Session\AccountInterface
     */
    protected $currentUser;
    
    /**
     * The entity type manager.
     *
     * @var \Drupal\Core\Entity\EntityTypeManagerInterface
     */
    protected $entityTypeManager;
    
    /**
     * The tempstore.
     *
     * @var \Drupal\Core\TempStore\SharedTempStore
     */
    protected $tempStore;
    
    /**
     * The messenger service.
     *
     * @var \Drupal\Core\Messenger\MessengerInterface
     */
    protected $messenger;
    
    /**
     * The entity type ID.
     *
     * @var string
     */
    protected $entityTypeId;
    
    /**
     * The selection, in the entity_id => langcodes format.
     *
     * @var array
     */
    protected $selection = [];
    
    /**
     * The entity type definition.
     *
     * @var \Drupal\Core\Entity\EntityTypeInterface
     */
    protected $entityType;
    
    /**
     * Constructs a new DeleteMultiple object.
     *
     * @param \Drupal\Core\Session\AccountInterface $current_user
     *   The current user.
     * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
     *   The entity type manager.
     * @param \Drupal\Core\TempStore\PrivateTempStoreFactory $temp_store_factory
     *   The tempstore factory.
     * @param \Drupal\Core\Messenger\MessengerInterface $messenger
     *   The messenger service.
     */
    public function __construct(AccountInterface $current_user, EntityTypeManagerInterface $entity_type_manager, PrivateTempStoreFactory $temp_store_factory, MessengerInterface $messenger) {
        $this->currentUser = $current_user;
        $this->entityTypeManager = $entity_type_manager;
        $this->tempStore = $temp_store_factory->get('entity_delete_multiple_confirm');
        $this->messenger = $messenger;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('current_user'), $container->get('entity_type.manager'), $container->get('tempstore.private'), $container->get('messenger'));
    }
    
    /**
     * {@inheritdoc}
     */
    public function getBaseFormId() {
        return 'entity_delete_multiple_confirm_form';
    }
    
    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        // Get entity type ID from the route because ::buildForm has not yet been
        // called.
        $entity_type_id = $this->getRouteMatch()
            ->getParameter('entity_type_id');
        return $entity_type_id . '_delete_multiple_confirm_form';
    }
    
    /**
     * {@inheritdoc}
     */
    public function getQuestion() {
        return $this->formatPlural(count($this->selection), 'Are you sure you want to delete this @item?', 'Are you sure you want to delete these @items?', [
            '@item' => $this->entityType
                ->getSingularLabel(),
            '@items' => $this->entityType
                ->getPluralLabel(),
        ]);
    }
    
    /**
     * {@inheritdoc}
     */
    public function getCancelUrl() {
        if ($this->entityType
            ->hasLinkTemplate('collection')) {
            return new Url('entity.' . $this->entityTypeId . '.collection');
        }
        else {
            return new Url('<front>');
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function getConfirmText() {
        return $this->t('Delete');
    }
    
    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state, $entity_type_id = NULL) {
        $this->entityTypeId = $entity_type_id;
        $this->entityType = $this->entityTypeManager
            ->getDefinition($this->entityTypeId);
        $this->selection = $this->tempStore
            ->get($this->currentUser
            ->id() . ':' . $entity_type_id);
        if (empty($this->entityTypeId) || empty($this->selection)) {
            return new RedirectResponse($this->getCancelUrl()
                ->setAbsolute()
                ->toString());
        }
        $items = [];
        $entities = $this->entityTypeManager
            ->getStorage($entity_type_id)
            ->loadMultiple(array_keys($this->selection));
        foreach ($this->selection as $id => $selected_langcodes) {
            $entity = $entities[$id];
            foreach ($selected_langcodes as $langcode) {
                $key = $id . ':' . $langcode;
                if ($entity instanceof TranslatableInterface) {
                    $entity = $entity->getTranslation($langcode);
                    $default_key = $id . ':' . $entity->getUntranslated()
                        ->language()
                        ->getId();
                    // Build a nested list of translations that will be deleted if the
                    // entity has multiple translations.
                    $entity_languages = $entity->getTranslationLanguages();
                    if (count($entity_languages) > 1 && $entity->isDefaultTranslation()) {
                        $names = [];
                        foreach ($entity_languages as $translation_langcode => $language) {
                            $names[] = $language->getName();
                            unset($items[$id . ':' . $translation_langcode]);
                        }
                        $items[$default_key] = [
                            'label' => [
                                '#markup' => $this->t('@label (Original translation) - <em>The following @entity_type translations will be deleted:</em>', [
                                    '@label' => $entity->label(),
                                    '@entity_type' => $this->entityType
                                        ->getSingularLabel(),
                                ]),
                            ],
                            'deleted_translations' => [
                                '#theme' => 'item_list',
                                '#items' => $names,
                            ],
                        ];
                    }
                    elseif (!isset($items[$default_key])) {
                        $items[$key] = $entity->label();
                    }
                }
                elseif (!isset($items[$key])) {
                    $items[$key] = $entity->label();
                }
            }
        }
        $form['entities'] = [
            '#theme' => 'item_list',
            '#items' => $items,
        ];
        $form = parent::buildForm($form, $form_state);
        return $form;
    }
    
    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        $total_count = 0;
        $delete_entities = [];
        $delete_translations = [];
        $inaccessible_entities = [];
        $storage = $this->entityTypeManager
            ->getStorage($this->entityTypeId);
        $entities = $storage->loadMultiple(array_keys($this->selection));
        foreach ($this->selection as $id => $selected_langcodes) {
            $entity = $entities[$id];
            if (!$entity->access('delete', $this->currentUser)) {
                $inaccessible_entities[] = $entity;
                continue;
            }
            foreach ($selected_langcodes as $langcode) {
                if ($entity instanceof TranslatableInterface) {
                    $entity = $entity->getTranslation($langcode);
                    // If the entity is the default translation then deleting it will
                    // delete all the translations.
                    if ($entity->isDefaultTranslation()) {
                        $delete_entities[$id] = $entity;
                        // If there are translations already marked for deletion then remove
                        // them as they will be deleted anyway.
                        unset($delete_translations[$id]);
                        // Update the total count. Since a single delete will delete all
                        // translations, we need to add the number of translations to the
                        // count.
                        $total_count += count($entity->getTranslationLanguages());
                    }
                    elseif (!isset($delete_entities[$id])) {
                        $delete_translations[$id][] = $entity;
                    }
                }
                elseif (!isset($delete_entities[$id])) {
                    $delete_entities[$id] = $entity;
                    $total_count++;
                }
            }
        }
        if ($delete_entities) {
            $storage->delete($delete_entities);
            foreach ($delete_entities as $entity) {
                $this->logger($entity->getEntityType()
                    ->getProvider())
                    ->notice('The @entity-type %label has been deleted.', [
                    '@entity-type' => $entity->getEntityType()
                        ->getSingularLabel(),
                    '%label' => $entity->label(),
                ]);
            }
        }
        if ($delete_translations) {
            
            /** @var \Drupal\Core\Entity\TranslatableInterface[][] $delete_translations */
            foreach ($delete_translations as $id => $translations) {
                $entity = $entities[$id]->getUntranslated();
                foreach ($translations as $translation) {
                    $entity->removeTranslation($translation->language()
                        ->getId());
                }
                $entity->save();
                foreach ($translations as $translation) {
                    $this->logger($entity->getEntityType()
                        ->getProvider())
                        ->notice('The @entity-type %label @language translation has been deleted.', [
                        '@entity-type' => $entity->getEntityType()
                            ->getSingularLabel(),
                        '%label' => $entity->label(),
                        '@language' => $translation->language()
                            ->getName(),
                    ]);
                }
                $total_count += count($translations);
            }
        }
        if ($total_count) {
            $this->messenger
                ->addStatus($this->getDeletedMessage($total_count));
        }
        if ($inaccessible_entities) {
            $this->messenger
                ->addWarning($this->getInaccessibleMessage(count($inaccessible_entities)));
        }
        $this->tempStore
            ->delete($this->currentUser
            ->id());
        $form_state->setRedirectUrl($this->getCancelUrl());
    }
    
    /**
     * Returns the message to show the user after an item was deleted.
     *
     * @param int $count
     *   Count of deleted translations.
     *
     * @return \Drupal\Core\StringTranslation\TranslatableMarkup
     *   The item deleted message.
     */
    protected function getDeletedMessage($count) {
        return $this->formatPlural($count, 'Deleted @count item.', 'Deleted @count items.');
    }
    
    /**
     * Returns the message to show the user when an item has not been deleted.
     *
     * @param int $count
     *   Count of deleted translations.
     *
     * @return \Drupal\Core\StringTranslation\TranslatableMarkup
     *   The item inaccessible message.
     */
    protected function getInaccessibleMessage($count) {
        return $this->formatPlural($count, "@count item has not been deleted because you do not have the necessary permissions.", "@count items have not been deleted because you do not have the necessary permissions.");
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
ConfirmFormBase::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormInterface::getCancelText 2
ConfirmFormBase::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormInterface::getDescription 15
ConfirmFormBase::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides ConfirmFormInterface::getFormName
DeleteMultipleForm::$currentUser protected property The current user.
DeleteMultipleForm::$entityType protected property The entity type definition.
DeleteMultipleForm::$entityTypeId protected property The entity type ID.
DeleteMultipleForm::$entityTypeManager protected property The entity type manager.
DeleteMultipleForm::$messenger protected property The messenger service. Overrides MessengerTrait::$messenger
DeleteMultipleForm::$selection protected property The selection, in the entity_id =&gt; langcodes format.
DeleteMultipleForm::$tempStore protected property The tempstore.
DeleteMultipleForm::buildForm public function Form constructor. Overrides ConfirmFormBase::buildForm
DeleteMultipleForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
DeleteMultipleForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId
DeleteMultipleForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl 2
DeleteMultipleForm::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormBase::getConfirmText
DeleteMultipleForm::getDeletedMessage protected function Returns the message to show the user after an item was deleted. 2
DeleteMultipleForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
DeleteMultipleForm::getInaccessibleMessage protected function Returns the message to show the user when an item has not been deleted. 2
DeleteMultipleForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion 1
DeleteMultipleForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
DeleteMultipleForm::__construct public function Constructs a new DeleteMultiple object.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
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::redirect protected function Returns a redirect response object for the specified route.
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 73
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 public function Gets the messenger. 17
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a &#039;destination&#039; 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. 3
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.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.