Major Productions
Major Productions

Reputation: 6042

Symfony2: form_widget call in twig throws exception "Catchable fatal error ... must be an instance of Symfony\Component\Form\FormView"

When I create a form inside my controller action like this:

$form = $this->createFormBuilder()
    ->add('field_name')
    ->getForm();

return array(
    'form' => $form
);

... and I try to render this form in a twig template like this:

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

... the form_widget invocation produces the following exception/error:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Argument 1 passed to Symfony\Component\Form\FormRenderer::searchAndRenderBlock() must be an instance of Symfony\Component\Form\FormView, instance of Symfony\Component\Form\Form given, called in ...

How can I resolve this issue?

Upvotes: 21

Views: 18359

Answers (2)

Ruben Guix Fernandez
Ruben Guix Fernandez

Reputation: 21

In Your Controller:

return array(
    'form' => $form->createView()
);

But if you want to send it to the view, it's a standard example:

return $this->render('@App/public/index.html.twig', array(
    'form'=>$form->createView()
));

Upvotes: 2

Nicolai Fr&#246;hlich
Nicolai Fr&#246;hlich

Reputation: 52493

You have to pass an instance of Symfony\Component\Form\FormView instead of Symfony\Component\Form\Form to your view.

Fix this using ...

... ->getForm()->createView();

FormBuilder::getForm builds the Form object ... Form::createView then creates a FormView object.

Upvotes: 52

Related Questions