7

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?

2 Answers 2

2
+50

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your reply! Actually, I've been there already, but I'm not entirely clear on how I can cleanly and dynamically add or remove content elements and media using the generated form-field prototypes. My solution so far is to add n empty content elements, each containing m empty media elements. This constraints the number of contents and media I can add. I'd rather use the built-in prototyping for dynamically adding content elements, but I don't know how to dynamically add associated media then.
-1
<form action="{{ path('article_create') }}" method="post" {{ form_enctype(form) }}>
    {% for media in form.contents.medias.children %}
         {{ form_widget(media) }}
    {% endfor %}
    {{ form_rest(form) }}
    <p>
        <button type="submit">Create</button>
    </p>
</form>

1 Comment

Care to add some comments to your code so is more clear and understable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.