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


How to show an alert message on delete of parent node in symfony2 instead of exception page?

hi每个人都是symfony2 的新手

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

服务与电子邮件服务和时事通讯服务有着一一对应的关系。

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

异常页面。例如,用户jhon拥有删除的网络和时事通讯服务

的用户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`))

请相应地指导我,提前感谢

您可以捕获ForeignKeyConstraintViolationException异常并向用户显示一条闪烁消息。

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.");
}