DashboardDeleteForm.php in Draggable dashboard 8
File
src/Form/DashboardDeleteForm.php
View source
<?php
namespace Drupal\draggable_dashboard\Form;
use Drupal\block\Entity\Block;
use Drupal\Core\Block\BlockManagerInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\draggable_dashboard\Entity\DashboardEntity;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class DashboardDeleteForm extends ConfirmFormBase {
protected $dashboard;
protected $blockManager;
public function __construct(BlockManagerInterface $block_manager) {
$this->blockManager = $block_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('plugin.manager.block'));
}
public function getFormId() {
return 'draggable_dashboard_delete_form';
}
public function getQuestion() {
return $this
->t('Are you sure you want delete dashboard `%title`?', [
'%title' => $this->dashboard
->get('title'),
]);
}
public function getConfirmText() {
return $this
->t('Delete');
}
public function getCancelUrl() {
return new Url('draggable_dashboard.overview');
}
public function buildForm(array $form, FormStateInterface $form_state, $did = '') {
if (!($this->dashboard = DashboardEntity::load($did))) {
throw new NotFoundHttpException();
}
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$blocks = json_decode($this->dashboard
->get('blocks'), TRUE);
foreach ($blocks as $relation) {
$block = Block::load($relation['bid']);
if ($block) {
$block
->delete();
}
}
$this
->logger('user')
->notice('Deleted `%title`', [
'%title' => $this->dashboard
->get('title'),
]);
$this
->messenger()
->addMessage($this
->t('The dashboard `%title` was deleted.', [
'%title' => $this->dashboard
->get('title'),
]));
$this->dashboard
->delete();
$this->blockManager
->clearCachedDefinitions();
$form_state
->setRedirectUrl($this
->getCancelUrl());
}
}