Claus Marin Kaiser
Claus Marin Kaiser

Reputation: 37

Twig form with dynamic name

I'm trying to print out the same form a random amount of times with Symfony and Twig, but I can't seem to figure it out.

What I've come up with so far is creating X amount of forms in the controller as so..

foreach ($participations as $e) {
        $id = $e->getId();
        $formName = "form_doc_".$id;
        ${$formName} = $this->createForm(DocumentType::class, $documentation);
        $viewVar[$formName] = ${$formName}->createView();
    }

In TWIG I'm setting string variable respectively as $formName from above and using this variable to set up a form attribute.

{% set formName = "form_doc_" ~ participation.id %}
{% set subForm = attribute(form, formName) %}
{{ form_start(subForm) }}
{{ form_widget(subForm.path) }}
{{ form_end(subForm) }}

When I'm trying to print the form I get an error saying.

"Neither the property "form_doc_40" nor one of the methods "form_doc_40()", "getform_doc_40()"/"isform_doc_40()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView" in admin/volunteerParticipations.html.twig at line 97"

Hope theres someone out there who can help me out ;) Thx

Upvotes: 0

Views: 2072

Answers (1)

Kep
Kep

Reputation: 5857

You can probably try using an array of forms like this:

Controller:

/**
 * @Route("/example", name="example_action")
 * @Template("example.html.twig")
 */
public function exampleAction(Request $request)
{
    $forms = array();
    $views = array();
    foreach ($participations as $e) {
        $form = $this->createForm(DocumentType::class, $documentation);
        $forms[] = $form;
        $views[] = $form->createView();
    }

    foreach ($forms as $form)
    {
        $form->handleRequest($request);

        if (!$form->isSubmitted()) continue;

        if ($form->isValid())
        {
            // Normal form stuff, eg. persisting
        }
    }

    // return views to twig template
    return array("forms" => $views);
}

View:

{%- for form in forms -%}
    {{ form_start(form) }}
    {{ form_widget(form.path) }}
    {{ form_end(form) }}
{%- endfor -%}

Upvotes: 1

Related Questions