larscm larscm - 3 months ago 44
PHP Question

Symfony 3 - static CollectionType children not showing up

I am working on a form in Symfony 3.1.3 and want to add a dynamic amount of checkboxes using

CollectionType
. In the
buildForm
-method of my
Type
-class I am using this code to add the Checkboxes:

$builder->add('levels', CollectionType::class, array(
'entry_type' => CheckboxType::class,
'mapped' => false,
));

foreach($levels as $level) {
$name = 'level_cb_'.$level['name'];
$builder->get('levels')->add($name, CheckboxType::class, array(
'label' => $level['name'],
'required' => false,
'mapped' => false,
));
}


If I call
var_dump($builder->get('levels'));
immediately afterwards the checkboxes show up in the
children
and
unresolvedChildren
properties of the
CollectionType
. Later I call
{{ dump(form.levels) }}
in the associated template and it shows me that the
children
property is empty.

Am I missing something obvious?

Answer

So it seems that the children of the collection get cleared somewhere between being added in my custom Type and the form being made available in the Controller.

I put the code to add the checkboxes into the controller and suddenly everything worked as expected. Maybe someone knows the reason behind that.

So in my SpecialType.php I just have:

    $builder->add('levels', CollectionType::class, array(
        'entry_type' => CheckboxType::class,
        'required' => false,
        'mapped' => false,
    ));

And in my SpecialFormController.php I have:

    $form = $this->createForm(SpecialType::class, $entity);
    foreach($levels as $level) {
        $name = 'level_cb_'.$level['name'];
        $form->get('levels')->add($name, CheckboxType::class, array(
            'label' => $level['name'],
            'required' => false,
            'mapped' => false,
        ));
    }