Question

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?


UPDATE 1

Part of Twig template (requested by Max):

{% 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 %}
Was it helpful?

Solution 2

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.

OTHER TIPS

You need to create:

  1. form class
  2. template of a form (with macro)
  3. jQuery script to manipulate the data in the form

Check this tutorial :)

http://toni.uebernickel.info/2012/03/15/an-example-of-symfony2-collectiontype-form-field-prototype.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top