Zoha Ali Khan
Zoha Ali Khan

Reputation: 1699

Check that record is successfully inserted in Symfony2

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?

Upvotes: 6

Views: 10240

Answers (1)

Chris McKinnel
Chris McKinnel

Reputation: 15082

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.

Upvotes: 23

Related Questions