Update and Insert data in database with doctrine2 and Symfony2

Today I want to present you the easiest way to update, extract and insert data in database by using the doctrine2 and Symfony2.6. This way i have seen on symfony.com.

So, my have a table in my database:

CREATE TABLE IF NOT EXISTS `test` (
`id` int(11) NOT NULL,
`text` longtext COLLATE utf8_unicode_ci NOT NULL
)

To insert new information in this table, I will use this code:

$test= new test();
$test->setText('A Foo Bar');

$em = $this->getDoctrine()->getManager();

$em->persist($test);
$em->flush();

in my controller.

To update data in my table, I will use this code:

public function updateAction($id)
{
$em = $this->getDoctrine()->getManager();
$test = $em->getRepository('NewBundle:Test')->find($id);

if (!$test) {
throw $this->createNotFoundException(
'No data found for id '.$id
);
}

$test>setText('New data!');
$em->flush();

}

in my controller. In this way I will update the data from my database.

If I want to display the data on a page, I will use this code:

public function showAction($id)
{
$test = $this->getDoctrine()
->getRepository('NewBundle:Test')
->find($id);

if (!$test) {
throw $this->createNotFoundException(
'No data found for id '.$id
);
}

}

in my controller.

As you can see, its very simple to use the Doctrine and Symfony.

Video tutorial:









Leave a Comment