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

Long Live The Network

The Storm Is Here # Today (or yesterday, depending on where you live), NiceHash got hacked. Approximately $64 million is reported to be stolen. Today is going to be “just another day in the crypto world”. People will make a fuss about... Continue →