formssymfonysymfony2

Binding request to a form does not work for collection type


I don't use any ORM for entities. This form is built for sending email only.

In my Controller I have this:

    $builder = $this->myHelper
        ->createBuilder('form', null)

        ->add('my_group', 'collection', array(
        'type' => 'text',
        'label' => 'mylabel'
    ));

    $builder->get('my_group')->add('first_node', 'text');
    $builder->get('my_group')->add('second_node', 'text');

    return $builder->getForm();

The form is rendered OK - with additional input fields as expected. But when it comes to binding request to form in my post-data handling action - my_group field comes empty (even due to fact that this field is posted in 'form' array):

// var_dump($request->get('form'));die;
array
 'my_group' => 
   array
     'first_node' => string 'asdasd' (length=3)
     'second_node' => string 'asdasda' (length=3)

When I bind request to form, I have null in my_group collection field (all other inputs are OK).

$form->bindRequest($request);
$formData = $form->getData();
var_dump($formData);die; // Outputs my_group => null

What am I doing wrong?

Part of Twig template:

{% for field in form.children if 'hidden' not in field.vars.types %}
    ...
    {% elseif 'collection' in field.vars.types %}
        <th>{{ form_label(field) }}</th>
        <td>
            {% for collection_field in field %}
                {{ form_widget(collection_field) }}
            {% endfor %}
        </td>
    {% else %}
    ...
{% endfor %}

Solution

  • My problem was solved, when I defined FormType for needed collection:

    class MyType extends AbstractType
    {
        public function buildForm(FormBuilder $builder, array $options)
        {
            $builder->add('first_node', 'text');
            $builder->add('second_node', 'text');
        }
    
        public function getDefaultOptions(array $options)
        {
            return array();
        }
    
        public function getName()
        {
            return 'mytype';
        }
    }
    

    Then I used it in builder:

    $builder = $this->myHelper
        ->createBuilder('form', null)
    
        ->add('my_group', new MyType(), array(
        'label' => 'mylabel'
    ));
    
    
    return $builder->getForm();
    

    After this data was bound to form correctly.