Verify that the record is successfully inserted into Symfony2

How to check if a record is successfully inserted into the database using Doctrine in symfony2?

My action in the controller

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 an if ?

+6
source share
1 answer

You can put your controller in a try / catch 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 failed, an exception will be thrown and caught. You might also want to log the error message inside your catch block in some way by calling $e->getMessage() and / or $e->getTraceAsString() , which will explain this exception.

+19
source

Source: https://habr.com/ru/post/916866/


All Articles