Here is written how to set the name of a form with a class:
http://symfony.com/doc/2.0/book/forms.html#creating-form-classes
but how to set the name of this
There is no shortcut method for this purpose. Instead you have to access the method createNamedBuilder
in the form factory:
$this->get('form.factory')->createNamedBuilder('form', 'form_name', $defaultData)
->add('name', 'text')
->add('email', 'email')
->getForm();
Is there any reason why you don't just do:
$data = $form->getData();
In version 2.4.1 of Symfony, the solution is:
$form = $this->createFormBuilder ( NULL, array ( 'attr' => array ( 'name' => 'myFormName', 'id' => 'myFormId' ) ) )
->add (..
You can also set other form attributes this way, but I've not tried. Replace NULL with your data if you want.
I would like to bring some more precision. At least, for the most recent version of Symfony (2.1), the correct symtax (documented on the API) is:
<?php
public FormBuilderInterface createNamedBuilder(string $name, string|FormTypeInterface $type = 'form', mixed $data = null, array $options = array(), FormBuilderInterface $parent = null)
It is important because you can still pass options to the FormBuilder. For a more concrete example:
<?php
$form = $this->get('form.factory')->createNamedBuilder('user', 'form', null, array(
'constraints' => $collectionConstraint,
))
->add('name', 'text')
->add('email', 'email')
->getForm();
If you're using Symfony 3.1, the field types have changed to use their explicit class (FormType
, TextType
, and EmailType
) and the parameter position for the value of the form name
attribute has switched places with the FormType
parameter in the createNamedBuilder function.
$this->get('form.factory')
->createNamedBuilder('form_name', FormType::class, $defaultData)
->add('name', TextType::class)
->add('email', EmailType::class)
->getForm();