RedirectDeleteMultipleForm.php in Redirect 8
File
src/Form/RedirectDeleteMultipleForm.php
View source
<?php
namespace Drupal\redirect\Form;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
class RedirectDeleteMultipleForm extends ConfirmFormBase {
protected $redirects = [];
protected $privateTempStoreFactory;
protected $redirectStorage;
protected $currentUser;
public function __construct(PrivateTempStoreFactory $temp_store_factory, EntityTypeManagerInterface $entity_type_manager, AccountInterface $account, TranslationInterface $string_translation) {
$this->privateTempStoreFactory = $temp_store_factory;
$this->redirectStorage = $entity_type_manager
->getStorage('redirect');
$this->currentUser = $account;
$this
->setStringTranslation($string_translation);
}
public static function create(ContainerInterface $container) {
return new static($container
->get('tempstore.private'), $container
->get('entity_type.manager'), $container
->get('current_user'), $container
->get('string_translation'));
}
public function getFormId() {
return 'redirect_multiple_delete_confirm';
}
public function getQuestion() {
return $this
->formatPlural(count($this->redirects), 'Are you sure you want to delete this redirect?', 'Are you sure you want to delete these redirects?');
}
public function getCancelUrl() {
return new Url('redirect.list');
}
public function getConfirmText() {
return $this
->t('Delete');
}
public function buildForm(array $form, FormStateInterface $form_state) {
$this->redirects = $this->privateTempStoreFactory
->get('redirect_multiple_delete_confirm')
->get($this->currentUser
->id());
if (empty($this->redirects)) {
return new RedirectResponse($this
->getCancelUrl()
->setAbsolute()
->toString());
}
$form['redirects'] = [
'#theme' => 'item_list',
'#items' => array_map(function ($redirect) {
return $redirect
->label();
}, $this->redirects),
];
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
if ($form_state
->getValue('confirm') && !empty($this->redirects)) {
$this->redirectStorage
->delete($this->redirects);
$this->privateTempStoreFactory
->get('redirect_multiple_delete_confirm')
->delete($this->currentUser
->id());
$count = count($this->redirects);
$this
->logger('redirect')
->notice('Deleted @count redirects.', [
'@count' => $count,
]);
$this
->messenger()
->addMessage($this->stringTranslation
->formatPlural($count, 'Deleted 1 redirect.', 'Deleted @count redirects.'));
}
$form_state
->setRedirect('redirect.list');
}
}