Pre-filling a silex form

Let’s say you want to populate another form with some data (on a GET request). This is a single-page Silex app and not a full Symfony2 stack with object based forms. We are talking about a form that uses simple array as its data model here.

The form is generated with the following piece of code:

$app->register(new \Silex\Provider\FormServiceProvider());
$app->register(new Silex\Provider\ValidatorServiceProvider());
$app->register(new \Silex\Provider\SessionServiceProvider());
$app->register(
    new Silex\Provider\TranslationServiceProvider(),
    array(
        'translator.domains' => array(),
    )
);

$form = $app['form.factory']->createBuilder('form')
    ->add('name','text',['label'=>'Full name'])
    // Add other forms fields here.
    ->getForm();

Assuming the pre-fill data is stored in the key-value array $data. My first attempt to fill the form was:

$form->submit($data);

This works! However, submitting a form also triggers the validation logic and displays error messages (e.g. on required fields).

Then I found:

$form->setData($data);

For some reason, the above line did not work. It turns out that you cannot set the data directly on a form, but you can do so via the form builder. The final, working solution is.

$formBuilder = $app['form.factory']->createBuilder('form')
    ->add('name','text',['label'=>'Full name'])
    // Add other forms fields here.
;
$form = $formBuilder->setData($data)->getForm();

By the way, don’t put the pre-fill values on the URL ($request->get('...')), it’s ugly and not cool for security, nor via POST parameters as the data is not the final submission. I think Session with a prefill=1 GET parameter can be a good fit here.

 
17
Kudos
 
17
Kudos

Now read this

Don’t (just) follow your passion

Nowadays, follow your passion has become a motto. I believe it is overrated. Passion can come and go in the blink of an eye. Because of its intensity, people sometimes mistake it as the substance although it is, in truth, nothing more... Continue →