21.10.2015 Views

1-33

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Symfony2 – Franz Jordán 2011<br />

If you click the icon, the profiler will open, showing you the exact queries that were made.<br />

Updating an Object<br />

Once you've fetched an object from Doctrine, updating it is easy. Suppose you have a route that<br />

maps a product id to an update action in a controller:<br />

public function updateAction($id)<br />

{<br />

$em = $this->getDoctrine()->getEntityManager();<br />

$product = $em->getRepository('AcmeStoreBundle:Product')->find($id);<br />

if (!$product) {<br />

}<br />

throw $this->createNotFoundException('No product found for id '.$id);<br />

$product->setName('New product name!');<br />

$em->flush();<br />

}<br />

return $this->redirect($this->generateUrl('homepage'));<br />

Updating an object involves just three steps:<br />

1. fetching the object from Doctrine;<br />

2. modifying the object;<br />

3. calling flush() on the entity manager<br />

Notice that calling $em->persist($product) isn't necessary. Recall that this method simply tells<br />

Doctrine to manage or "watch" the $product object. In this case, since you fetched<br />

the $productobject from Doctrine, it's already managed.<br />

90

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!