Permalink
Browse files

Display a proper error message when a database item cannot be removed

  • Loading branch information...
1 parent 58ad5e5 commit 570f6a87a0015e41a0d59d55b4089c76e06921f1 @javiereguiluz committed Nov 19, 2016
Showing with 34 additions and 2 deletions.
  1. +8 −2 Controller/AdminController.php
  2. +26 −0 Exception/EntityRemoveException.php
@@ -11,9 +11,11 @@
namespace JavierEguiluz\Bundle\EasyAdminBundle\Controller;
+use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\QueryBuilder;
use JavierEguiluz\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
+use JavierEguiluz\Bundle\EasyAdminBundle\Exception\EntityRemoveException;
use JavierEguiluz\Bundle\EasyAdminBundle\Exception\ForbiddenActionException;
use JavierEguiluz\Bundle\EasyAdminBundle\Exception\NoEntitiesConfiguredException;
use JavierEguiluz\Bundle\EasyAdminBundle\Exception\UndefinedEntityException;
@@ -332,8 +334,12 @@ protected function deleteAction()
$this->executeDynamicMethod('preRemove<EntityName>Entity', array($entity));
- $this->em->remove($entity);
- $this->em->flush();
+ try {
+ $this->em->remove($entity);
+ $this->em->flush();
+ } catch (ForeignKeyConstraintViolationException $e) {
+ throw new EntityRemoveException(array('entity' => $this->entity['name']));
+ }
$this->dispatch(EasyAdminEvents::POST_REMOVE, array('entity' => $entity));
}
@@ -0,0 +1,26 @@
+<?php
+
+/*
+ * This file is part of the EasyAdminBundle.
+ *
+ * (c) Javier Eguiluz <javier.eguiluz@gmail.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace JavierEguiluz\Bundle\EasyAdminBundle\Exception;
+
+/**
+ * @author Javier Eguiluz <javier.eguiluz@gmail.com>
+ */
+class EntityRemoveException extends BaseException
+{
+ public function __construct(array $parameters = array())
+ {
+ $errorMessage = sprintf('You can\'t delete this "%s" item because other items depend on it in the database.', $parameters['entity']);
+ $proposedSolution = "Don't delete this item or change the database configuration to allow deleting it.";
+
+ parent::__construct($errorMessage, $proposedSolution, 404);
+ }
+}

0 comments on commit 570f6a8

Please sign in to comment.