我有一个问题,Symfony2 表单可以通过验证,但在提交表单时仍会生成由唯一约束引起的 Doctrine2 异常。我可以捕捉到这个 PDOException,但我想做的是使表单无效并设置一个表单错误,指示实体的特定属性是重复的。我的代码是:
$entity = new Tag();
$request = $this->getRequest();
$form = $this->createForm(new \Acme\AdminBundle\Form\Tag(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
try {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('tag_edit', array('id' => $entity->getTagId())));
} catch( ORM\PDOException $e) {
if ($e->getCode() === '23000') {
// What do I do here??
}
}
}
return array(
'entity' => $entity,
'form' => $form->createView()
);