Justinas Lelys
Justinas Lelys

Reputation: 632

Symfony2 render form for each list item

How could I achieve a form for each list item using csrf and validation in symfony way?

I have a Task entity, which has comments property with a relation OneToMany. So I want to list all tasks and include a hidden comment form for every task. Usually I pass generated forms from controller to template, but how to create them dinamically in template?

{% for task in tasks %}
<taskinfo>
<task comment form>
{% endfor %}

Upvotes: 0

Views: 1176

Answers (2)

Justinas Lelys
Justinas Lelys

Reputation: 632

Solved using this way:

In controller:

    $forms = array();
    foreach($tasks as $task) {
        $entity = new TaskComment();
        $forms[$task -> getId()] = $this ->createTaskCommentForm($entity, $task -> getId());
    }
   return $this->render('Bundle:blah:index.html.twig', array(
        ....
        'forms' => $forms
    ));

An then comment box near every Task box in view:

    ...task info...
    {% for task in tasks %}
        <div class="comment-box">
             {{ form(forms[task.id]) }}
        </div>
    {% endfor %}

P.S. I'm using collapsible panels to show/hide each task.

Upvotes: 1

Serge Kvashnin
Serge Kvashnin

Reputation: 4491

Maybe you need to embed a collection of forms? If so, here and here you can read more.

Upvotes: 0

Related Questions