Symfony & Doctrine: Using try… catch to determine success or failure of database insert or update action

In Doctrine, there is no simple way to access the Doctrine object and get the status of the last attempt at inserting or updating the database. To overcome this glaring limitation of the DBAL (Database Abstraction Layer), we have to resort to older PHP techniques like using a try… catch condition.

Seems like a lot of code to do something we old-school PHP devs have been able to do with the mysql object for a decade now, but this is the reality of it.

try {
        $symfonyEntity= new symfonyEntity();
        $symfonyEntity->setTitle('Symfony Entity Title');
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($dataObject);
        $em->flush();

        $this->get('session')->setFlash('flashMsg',"Record inserted");

    } catch (Exception $e) {
        $this->get('session')->setFlash('flashMsg',"Record not inserted");
    }

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *