access_policy-1.0.x-dev/modules/access_policy_ui/src/Form/AccessPolicyDeleteForm.php
modules/access_policy_ui/src/Form/AccessPolicyDeleteForm.php
<?php namespace Drupal\access_policy_ui\Form; use Drupal\Core\Entity\EntityConfirmFormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Url; /** * Builds the form to delete AccessPolicy entities. */ class AccessPolicyDeleteForm extends EntityConfirmFormBase { /** * Flag indicating whether this policy is being used. * * @var bool */ protected $isUsed; /** * {@inheritdoc} */ public function getQuestion() { return $this->t('Are you sure you want to delete @name?', ['@name' => $this->entity->label()]); } /** * {@inheritdoc} */ public function getDescription() { if ($this->isUsed()) { return $this->t('The access policy @name is being used, and cannot be deleted.', ['@name' => $this->entity->label()]); } return parent::getDescription(); } /** * {@inheritdoc} */ public function getCancelUrl() { return new Url('entity.access_policy.collection'); } /** * {@inheritdoc} */ public function getConfirmText() { return $this->t('Delete'); } /** * {@inheritdoc} */ protected function actions(array $form, FormStateInterface $form_state) { $actions = parent::actions($form, $form_state); if ($this->isUsed()) { unset($actions['submit']); } return $actions; } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $this->entity->delete(); $this->messenger()->addMessage( $this->t('Deleted @label Access Policy.', [ '@label' => $this->entity->label(), ] ) ); $form_state->setRedirectUrl($this->getCancelUrl()); } /** * Determine whether this access policy is being used. * * @return bool * TRUE if it's being used; FALSE otherwise. */ private function isUsed() { if (!isset($this->isUsed)) { $this->isUsed = FALSE; $entity_type = $this->getEntity()->getTargetEntityTypeId(); $query = $this->entityTypeManager->getStorage($entity_type)->getQuery(); $query->accessCheck(FALSE); $query->condition('access_policy', $this->getEntity()->id()); $query->count(); $count = $query->execute(); if ($count > 0) { $this->isUsed = TRUE; } } return $this->isUsed; } }