Symfony2 Form Entity Update

Jeremy Hicks picture Jeremy Hicks · Jul 7, 2011 · Viewed 52.4k times · Source

Can anyone please show me a specific example of a Symfony2 form entity update? The book only shows how to create a new entity. I need an example of how to update an existing entity where I initially pass the id of the entity on the query string.

I'm having trouble understanding how to access the form again in the code that checks for a post without re-creating the form.

And if I do recreate the form, it means I have to also query for the entity again, which doesn't seem to make much sense.

Here is what I currently have but it doesn't work because it overwrites the entity when the form gets posted.

public function updateAction($id)
{
    $em = $this->getDoctrine()->getEntityManager();
    $testimonial = $em->getRepository('MyBundle:Testimonial')->find($id);
    $form = $this->createForm(new TestimonialType(), $testimonial);

    $request = $this->get('request');
    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);

        echo $testimonial->getName();

        if ($form->isValid()) {
            // perform some action, such as save the object to the database
            //$testimonial = $form->getData();
            echo 'testimonial: ';
            echo var_dump($testimonial);
            $em->persist($testimonial);
            $em->flush();

            return $this->redirect($this->generateUrl('MyBundle_list_testimonials'));
        }
    }

    return $this->render('MyBundle:Testimonial:update.html.twig', array(
        'form' => $form->createView()
    ));
}

Answer

Jeremy Hicks picture Jeremy Hicks · Aug 1, 2011

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()
    ));
}