【问题标题】:How to set the name of a form without a class?如何设置没有类的表单名称?
【发布时间】:2011-10-17 15:29:06
【问题描述】:

这里写了如何使用类设置表单的名称:

http://symfony.com/doc/2.0/book/forms.html#creating-form-classes

但是如何设置这个表单的名字呢?

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

嗯,我正在尝试以这种方式提交后获取帖子参数:

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

【问题讨论】:

    标签: symfony


    【解决方案1】:

    我想更精确一些。至少,对于最新版本的 Symfony (2.1),正确的 symtax​​(记录在 API 中)是:

    <?php
    
         public FormBuilderInterface createNamedBuilder(string $name, string|FormTypeInterface $type = 'form', mixed $data = null, array $options = array(), FormBuilderInterface $parent = null)
    

    这很重要,因为您仍然可以将选项传递给 FormBuilder。 更具体的例子:

    <?php
    
     $form = $this->get('form.factory')->createNamedBuilder('user', 'form',  null, array(
        'constraints' => $collectionConstraint,
    ))
    ->add('name', 'text')
    ->add('email', 'email')
    ->getForm();
    

    【讨论】:

    • Symfony 3.1中,如果还想设置其他选项,解决方法是:$this-&gt;get('form.factory')-&gt;createNamedBuilder('yourFormName', FormType::class, null, ['option'=&gt;'value']
    【解决方案2】:

    为此没有捷径可走。相反,您必须在表单工厂中访问方法 createNamedBuilder

    $this->get('form.factory')->createNamedBuilder('form', 'form_name', $defaultData)
        ->add('name', 'text')
        ->add('email', 'email')
        ->getForm();
    

    【讨论】:

    • 据我所知,这对 Symfony2.3 仍然有效,对吗?仍然没有捷径。
    • 刚刚注意到,在 Symfony 2.3 中,参数是相反的......所以现在是 (name, type, defaults, options) .. see the docs
    【解决方案3】:

    如果您使用 Symfony 3.1,字段类型已更改为使用它们的显式类(FormTypeTextTypeEmailType),并且 name 属性形式的值的参数位置具有使用createNamedBuilder function 中的FormType 参数交换位置。

    $this->get('form.factory')
      ->createNamedBuilder('form_name', FormType::class, $defaultData)
      ->add('name', TextType::class)
      ->add('email', EmailType::class)
      ->getForm();
    

    【讨论】:

      【解决方案4】:

      你有什么理由不这样做:

      $data = $form->getData();
      

      【讨论】:

      • 是的,这行得通,但我必须在表单提交调用的操作中重新声明表单.. :)
      【解决方案5】:

      在 Symfony 2.4.1 版本中,解决方案是:

      $form = $this->createFormBuilder ( NULL, array ( 'attr' => array ( 'name' => 'myFormName', 'id' => 'myFormId' ) ) )
                  ->add (..
      

      你也可以这样设置其他表单属性,但我没试过。如果需要,请将 NULL 替换为您的数据。

      【讨论】:

      • 这不起作用,因为它呈现为&lt;form name="form" name="myFormName" /&gt;
      猜你喜欢
      • 1970-01-01
      • 2019-11-09
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多