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?
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.
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.
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.
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.
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()
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With