6

How can I check if a record is successfully inserted in database using Doctrine in symfony2?

My action in controller is

public function createAction(){
    $portfolio = new PmPortfolios();
    $portfolio->setPortfolioName('Umair Portfolio');
    $em = $this->getDoctrine()->getEntityManager();
    $em->persist($portfolio);
    $em->flush();
    if(){
         $this->get('session')->setFlash('my_flash_key',"Record Inserted!");
    }else{
         $this->get('session')->setFlash('my_flash_key',"Record notInserted!");
    }
}

What should I write in the if statement?

1 Answer 1

23

You could wrap your controller in a try / catch block like this:

public function createAction() {
    try {
        $portfolio = new PmPortfolios();
        $portfolio->setPortfolioName('Umair Portfolio');
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($portfolio);
        $em->flush();

        $this->get('session')->setFlash('my_flash_key',"Record Inserted!");

    } catch (Exception $e) {
        $this->get('session')->setFlash('my_flash_key',"Record notInserted!");
    }
}

If the insert fails, an exception will be thrown and caught. You will probably also want to log the error message inside your catch block somehow by calling $e->getMessage() and/or $e->getTraceAsString() which will explain the exception.

4
  • How can I display different divs in view according to success and fail of insertion? May 28, 2012 at 21:43
  • Add a flash message with a different key - like setFlash('insert_failed', 'Your message') and in your twig template do something like {% if app.session.hasFlash('insert_failed') %}<div class="error-message">{{ app.session.flash('insert_failed') }}</div>{% endif %} May 28, 2012 at 21:55
  • Maybe you should call the rollback-method of your entitymanager in the catch-block. Just FYI May 29, 2012 at 7:00
  • As far as I know, if flush() fails, the rollback will be done automatically. Jun 2, 2012 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.