Search code examples
symfonysymfony-formssymfony4formbuilder

How to fix 'Variable does not exist' when using FormBuilder?


I've worked through a few of the Forms-Tutorials on the Symfony-Page (especially How to Embed a Collection of Forms, How To use a Form without a Dataclass & CollectionType Field ).

I'm trying to show a form with multiple lead partners which can be edited and submitted back to the system.

But i get a Twig_Runtime_Error saying: ''Variable "lead_partners" does not exist''.

My Twig:

{% block content %}

<div>

    {{ form_start(form) }}
    {% for partner in lead_partners %}
        {{ form_row(partner.name) }}
    {% endfor %}
    {{ form_end(form) }}

</div>

{% endblock content %}

My Controller Code:

public function overview(Request $request, \App\Utility\LeadPartnerLoader $LeadPartnerLoader)
{
    $leadPartnerList = $LeadPartnerLoader->loadAll();

    $form = $this->createFormBuilder($leadPartnerList)
        ->add('lead_partners', CollectionType::class, [
            'entry_type' => LeadPartnerFormType::class,
        ])->getForm();

    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid())
    {
        $data = $form->getData();
    }

    return $this->render(
        'lead_partner_overview2.html.twig',
        [
            'form' => $form->createView()
        ]);
}

And the Form Type (LeadPartnerFormType):

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => LeadPartner::class,
    ));
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('id', HiddenType::class)
        ->add('name', TextType::class);
}

$leadPartnerList is of type array.

What am i doing wrong/missing here?

Kind Regards


Solution

  • It seems your action overview soesn't return the lead_partners variable you use in your template.

    You can try to do this

    return $this->render(
        'lead_partner_overview2.html.twig',
        [
            'form' => $form->createView(),
            'lead_partners' =>  $leadPartnerList, // I gess that's the list you want to loop ?
        ]);