Symfony2 Form Entity Update Symfony2 Form Entity Update symfony symfony

Symfony2 Form Entity Update


Working now. Had to tweak a few things:

public function updateAction($id){    $request = $this->get('request');    if (is_null($id)) {        $postData = $request->get('testimonial');        $id = $postData['id'];    }    $em = $this->getDoctrine()->getEntityManager();    $testimonial = $em->getRepository('MyBundle:Testimonial')->find($id);    $form = $this->createForm(new TestimonialType(), $testimonial);    if ($request->getMethod() == 'POST') {        $form->bindRequest($request);        if ($form->isValid()) {            // perform some action, such as save the object to the database            $em->flush();            return $this->redirect($this->generateUrl('MyBundle_list_testimonials'));        }    }    return $this->render('MyBundle:Testimonial:update.html.twig', array(        'form' => $form->createView()    ));}


This is actually a native function of Symfony 2 :

You can generate automatically a CRUD controller from the command line (via doctrine:generate:crud) and the reuse the generated code.

Documentation here :http://symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/generate_doctrine_crud.html


A quick look at the auto-generated CRUD code by the Symfony's command generate:doctrine:crudshows the following source code for the edit action

/**     * Displays a form to edit an existing product entity.     *     * @Route("/{id}/edit", name="product_edit")     * @Method({"GET", "POST"})     */    public function editAction(Request $request, Product $product)    {        $editForm = $this->createForm('AppBundle\Form\ProductType', $product);        $editForm->handleRequest($request);        if ($editForm->isSubmitted() && $editForm->isValid()) {            $this->getDoctrine()->getManager()->flush();            return $this->redirectToRoute('product_edit', array('id' => $product->getId()));        }        return $this->render('product/edit.html.twig', array(            'product' => $product,            'edit_form' => $editForm->createView(),        ));    }

Note that a Doctrine entity is passed to the action instead of an id (string or integer). This will make an implicit parameter conversion and saves you from manually fetching the corresponding entity with the given id.

It is mentioned as best practice in the Symfony's documentation