tirenweb
tirenweb

Reputation: 31709

How to set the name of a form without a class?

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 form?

$form = $this->createFormBuilder($defaultData)
    ->add('name', 'text')
    ->add('email', 'email')
    ->getForm();

Well, I'm trying to get post parameters after submitting it this way:

$postData = $request->request->get('form_name');

Upvotes: 19

Views: 26007

Answers (5)

Jeff Puckett
Jeff Puckett

Reputation: 40861

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();

Upvotes: 4

Rob Tyler
Rob Tyler

Reputation: 31

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.

Upvotes: 1

tobalsan
tobalsan

Reputation: 476

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();

Upvotes: 45

Bernhard Schussek
Bernhard Schussek

Reputation: 4841

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();

Upvotes: 14

igorw
igorw

Reputation: 28239

Is there any reason why you don't just do:

$data = $form->getData();

Upvotes: 3

Related Questions