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?
Check out the file vendor/doctrine/orm/lib/Doctrine/ORM/Version. php , there is a constant in there that shows the version. It's also accessible from a running app but this is easier.
A repository in a term used by many ORMs (Object Relational Mappers), doctrine is just one of these. It means the place where our data can be accessed from, a repository of data. This is to distinguish it from a database as a repository does not care how its data is stored.
Symfony provides all the tools you need to use databases in your applications thanks to Doctrine, the best set of PHP libraries to work with databases. These tools support relational databases like MySQL and PostgreSQL and also NoSQL databases like MongoDB.
Well, entity is a type of object that is used to hold data. Each instance of entity holds exactly one row of targeted database table. As for the directories, Symfony2 has some expectations where to find classes - that goes for entities as well.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With