如何在删除symfony2中的父节点而不是异常页面时显示警告消息?

Zar*_*tza 5 php database doctrine exception symfony

嗨,每个人都是symfony2的新手

我有一个用户实体与服务有一对多的关系

和服务与电子邮件服务和新闻通讯服务有一对一的关系.

我想在删除父节点上显示警告消息而不是

异常页面.例如,用户jhon具有关于删除的web和新闻通讯服务

用户jhon我希望显示一条警告消息而不是这个

 An exception occurred while executing 'DELETE FROM user WHERE id = ?' with 
 params ["21"]:

   SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or 
   update   a parent row: a foreign key constraint fails 
 (`mwanmobile_bi`.`service`, CONSTRAINT `FK_E19D9AD2A76ED395` FOREIGN KEY 
  (`user_id`) REFERENCES `user` (`id`))
Run Code Online (Sandbox Code Playgroud)

请提前告知我,谢谢

lso*_*uza 5

您可以捕获ForeignKeyConstraintViolationException异常并向用户显示Flash消息.

use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;

// Action
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('AppBundle:User')->find($id);

try {
    $em->remove($user);
    $em->flush();

    $this->addFlash('success', 'User removed');
} catch (ForeignKeyConstraintViolationException $e) {
    $this->addFlash('error', "This user has connected services, so it can't be removed.");
}
Run Code Online (Sandbox Code Playgroud)