Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle multiple nested Form Collections in Symfony 2.0?

I've got an extension to this question: How to deal with Form Collection on Symfony2 Beta? - My project is similar, but the objects are nested deeper. I've got Articles which have one or more Content elements, each of which contains one or more Media. The Model and Controllers are working fine so far, but I don't know how to properly represent the nesting in my template. Form/ContentType.php looks all right:

class ContentType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('headline')
            ->add('text')
            ->add('medias', 'collection', array(
              'type'      => new MediaType(),
              'allow_add' => true
            ))
        ;
    }

And so far, the form template for creating (or editing) an Article looks like this (almost vanilla auto-generated template):

...
<form action="{{ path('article_create') }}" method="post" {{ form_enctype(form) }}>
    {{ form_widget(form) }}

    {% for content in form.contents %}
        {{ form_widget(content) }}
    {% endfor %}

    <p>
        <button type="submit">Create</button>
    </p>
</form>
...

How do I access each Content's Media so they get properly associated?

like image 656
Fester Bestertester Avatar asked Sep 07 '11 15:09

Fester Bestertester


1 Answers

Iterate through all content's media:

<form action="{{ path('article_create') }}" method="post" {{ form_enctype(form) }}>
    {{ form_widget(form) }}

    {% for content in form.contents %}
        {% for media in content.medias %}
            {{ form_widget(media) }}
        {% endfor %}
    {% endfor %}

    <p>
        <button type="submit">Create</button>
    </p>
</form>
like image 105
Elvan Avatar answered Oct 14 '22 11:10

Elvan