Last Updated: February 25, 2016
·
12.55K
· charlybr

Symfony2: Catch Doctrine exception in the controller and set flash message

if ($form->isValid()) {
    try {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();
    } catch(\Doctrine\DBAL\DBALException $e) {
        $this->get('session')->getFlashBag()->add('error', 'Can\'t insert entity.');
        return $this->redirect($this->generateUrl('your_route'));
    }

    return $this->redirect($this->generateUrl('your_route_show', array('id' => $entity->getId())));
}