Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 894
Zoha Ali Khan Avatar asked May 28 '12 20:05

Zoha Ali Khan


People also ask

How do I know my doctrine version?

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.

What is doctrine repository?

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.

What is Doctrine in Symfony?

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.

What is an entity Symfony?

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.


1 Answers

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.

like image 119
Chris McKinnel Avatar answered Sep 17 '22 13:09

Chris McKinnel