Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 257
Major Productions Avatar asked Jul 10 '13 02:07

Major Productions


People also ask

What is the second argument to form_row() in twig?

The second argument to form_row () is an array of variables. The templates provided in Symfony only allow to override the label as shown in the example above. See "Twig Template Form Function and Variable Reference" to learn about the variables argument. This renders all fields that have not yet been rendered for the given form.

What is the second argument to form_ widget()?

The second argument to form_widget () is an array of variables. The most common variable is attr, which is an array of HTML attributes to apply to the HTML widget. In some cases, certain types also have other template-related options that can be passed. These are discussed on a type-by-type basis.

What is the current stable version of Symfony?

Warning: You are browsing the documentation for Symfony 4.0 , which is no longer maintained. Read the updated version of this page for Symfony 6.1 (the current stable version). When working with forms in a template, there are two powerful things at your disposal: Variables for getting any information about any field.


2 Answers

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.

like image 73
Nicolai Fröhlich Avatar answered Oct 02 '22 01:10

Nicolai Fröhlich


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()
));
like image 40
Ruben Guix Fernandez Avatar answered Oct 02 '22 02:10

Ruben Guix Fernandez