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());
    new Silex\Provider\TranslationServiceProvider(),
        '' => array(),

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

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


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

Then I found:


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.


Now read this

I’m getting a dish washer

Ok, really, this is not just about getting a dish washer. Hey Laura, I am just writing to let you know that I am going to buy a dish washer when we move to the new place. This is by no means my excuse to slack off. Let me explain to you... Continue →