Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Form pre-fill fields with data

Assume for a moment that this form utilizes an imaginary Animal document object class from a ZooCollection that has only two properties ("name" and "color") in symfony2.

I'm looking for a working simple stupid solution, to pre-fill the form fields with the given object auto-magically (eg. for updates ?).

Acme/DemoBundle/Controller/CustomController:

public function updateAnimalAction(Request $request)
{
    ...
    // Create the form and handle the request
    $form = $this->createForm(AnimalType(), $animal);

    // Set the data again          << doesn't work ?
    $form->setData($form->getData());
    $form->handleRequest($request);
    ...
}
like image 487
mate64 Avatar asked Dec 10 '13 16:12

mate64


2 Answers

You should load the animal object, which you want to update. createForm() will use the loaded object for filling up the field in your form.

Assuming you are using annotations to define your routes:

/**
 * @Route("/animal/{animal}")
 * @Method("PUT")
 */
public function updateAnimalAction(Request $request, Animal $animal) {
    $form = $this->createForm(AnimalType(), $animal, array(
        'method' => 'PUT', // You have to specify the method, if you are using PUT 
                           // method otherwise handleRequest() can't
                           // process your request.
    ));

    $form->handleRequest($request);
    if ($form->isValid()) {
        ...
    }
    ...
}

I think its always a good idea to learn from the code generated by Symfony and doctrine console commands (doctrine:generate:crud). You can learn the idea and the way you should handle this type of requests.

like image 124
dtengeri Avatar answered Nov 12 '22 17:11

dtengeri


Creating your form using the object is the best approach (see @dtengeri's answer). But you could also use $form->setData() with an associative array, and that sounds like what you were asking for. This is helpful when not using an ORM, or if you just need to change a subset of the form's data.

  • http://api.symfony.com/2.8/Symfony/Component/Form/Form.html#method_setData

The massive gotcha is that any default values in your form builder will not be overridden by setData(). This is counter-intuitive, but it's how Symfony works. Discussion:

  • https://github.com/symfony/symfony/issues/7141
like image 26
eukras Avatar answered Nov 12 '22 16:11

eukras