I have an issue in that a Symfony2 form can pass validation but still generate a Doctrine2 exception caused by a unique constraint when the form is submitted. I can catch this PDOException, but what I want to do is invalidate the form and set a form error indicating that a particular attribute of the entity is a duplicate. The code I have is:
$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()
);
I think you are looking for the UniqueEntity annotation.
If you use it, you won’t need the try/catch block, because a check will be performed before an insert is even attempted.