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

后端 未结 5 1936
小鲜肉
小鲜肉 2020-12-17 10:32

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

相关标签:
5条回答
  • 2020-12-17 10:48

    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();
    
    0 讨论(0)
  • 2020-12-17 10:57

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

    $data = $form->getData();
    
    0 讨论(0)
  • 2020-12-17 11:04

    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.

    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-12-17 11:09

    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();
    
    0 讨论(0)
提交回复
热议问题