Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload or clear data in existing form in Symfony2.1

We upgraded from Symfony 2.0 to 2.1. With 2.0, I used to modify the entity and reload the form like this:

$form->setData($entity);

But this is not allowed anymore with Symfony 2.1 (https://github.com/symfony/symfony/pull/3322). I get the following error:

You cannot change the data of a bound form

Is there a way to rebind the form to the entity/reload the data?

like image 821
Ben Avatar asked Sep 25 '12 21:09

Ben


1 Answers

I did something that did the trick… Don't know if it's best way but…

public function contactAction(Request $request){
    $task = new myBundle();

    $form = $this->createFormBuilder($task)
        ->add('email', 'text', array('label'=>'E-mail'))
        ->add('message', 'textarea')
        ->add('newsletter', 'checkbox', array('label'=>'blabla','required'=>false))
        ->getForm();

   $cloned = clone $form;

    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);
        if ($form->isValid()) {
            [... code ...]
            $form = $cloned;
        }
    }
    return $this->render(
         'myBundle:Default:contact.html.twig',
          array('form' => $form->createView())
     );
}

By cloning the just instanciated form object, I can switch the «full» one by the empty one, and keep all the params.

like image 72
Ophiuchus Avatar answered Nov 10 '22 19:11

Ophiuchus