Reputation: 1699
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
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