David Barreto
David Barreto

Reputation: 9497

Symfony2 embedded controller and form validation issue

I have a template for editing a franchise. Inside that template I have two things: an embedded controller who show me a summary table with all the franchise already stored in the database, with an "edit" button for each row, and the form filled with the data of the franchise I'm currently editing.

The problem is that when I process the form and the validation fails, the summary table created by the embedded controller, shows me the franchise I was trying to modify with the values that I entered in the form, even though it didn't pass the validation and the database was never updated.

The code has some spanish words so, just for clarification, "franquicia" means "franchise"

The method for rendering and validating the form is:

public function editarAction($superusuario_id, $franquicia_id)
{
    $request = $this->getRequest();

    $em = $this->getDoctrine()->getEntityManager();
    $franquicia = $em->getRepository('FacturaBundle:Franquicia')->findOneById($franquicia_id);

    $form = $this->createForm(new FranquiciaType(), $franquicia);

    if($request->getMethod() == 'POST') 
    {
        $form->bindRequest($request);
        if($form->isValid()) 
        {
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($franquicia);
            $em->flush();
            return $this->redirect($this->generateUrl('s_listar_franquicias', array('superusuario_id'=>$superusuario_id)));
        }
    }

    return $this->render('FacturaBundle:Superusuario:franquicia-editar.html.twig', 
                   array('superusuario_id'=>$superusuario_id, 
                         'franquicia_id'=>$franquicia_id, 
                         'form'=>$form->createView(),  
                         'franquicia'=>$franquicia ));
}

The method used by the embedded controller is:

public function listarTodasAction($superusuario_id)
{
    $em = $this->getDoctrine()->getEntityManager();
    $franquicias = $em->getRepository('FacturaBundle:Franquicia')->findAll();

    return $this->render('FacturaBundle:Superusuario:franquicia-listar-todas.html.twig', array('superusuario_id'=>$superusuario_id, 'franquicias'=>$franquicias));
}

I'm not pasting the code for the templates because it's too long but I will do it if needed.

Can anyone help me?

Upvotes: 0

Views: 678

Answers (1)

Cerad
Cerad

Reputation: 48865

The basic problem is that $form->bindRequest actually updates $franquicia with posted information. D2 caches everything so the changes show up later on. Use refresh to set it back to it's original data:

    if($form->isValid()) 
    {
        ...
    }
    $this->getDoctrine()->getEntityManager()->refresh($franquicia);

Upvotes: 2

Related Questions