我遇到一个问题,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()
);