【问题标题】:Symfony 2 form field radio required=false?Symfony 2表单字段收音机需要=假?
【发布时间】:2013-11-14 23:21:54
【问题描述】:

这是我的实体类的一部分:

/**
 * @var integer
 *
 * @ORM\Column(name="student", type="integer", nullable=true)
 */
private $student;

我的表单类的这一部分:

 $builder
    ->add('student', 'choice', ['label'=> false,
    'expanded' => true,
    'choices' => (Array)new StudentEnum(),
   ])
        ;

这是输出:

<input id="xxxxx_0" type="radio" value="4" required="required" name="xxxxx[student]">
<label class="required" for="xxxxxV_student_0">Nie</label>

...

我的问题是我的输入标签不应该有属性“必需”,因为我在实体中设置了 nullable=true。

【问题讨论】:

    标签: forms symfony doctrine-orm choice


    【解决方案1】:

    解决方案是required =&gt; falseempty_value =&gt; false

    $builder
            ->add('student', 'choice', [
                    'label'=> false,
                    'expanded' => true,
                    'choices' => (Array)new StudentEnum(),
                    'required' => false,
                    'empty_value' => false
            ]);
    

    【讨论】:

    • 这个解决方案在 Symfony 2.8 之前是好的,那么你必须使用 "placeholder" 选项,因为 "empty_value" 在 2.7 中已被弃用(并在 3.0 中被删除)
    【解决方案2】:

    here所述,

    required
    type: Boolean default: true
    

    required 选项默认值设置为true,因此您应该将其设置为false

    builder->add('student', 'choice', array(
              'label'=> false,
              'expanded' => true,
              'required' => false,
              //...
       ))
    ;
    

    此外,您可以从文档中了解到,

    这是肤浅的,独立于验证。充其量,如果你让 Symfony 猜你的字段类型,那么这个选项的值将从你的 验证信息。

    然后,您需要设置一个验证规则,考虑到您的字段不应该是必需的事实,以便让您的表单设置正确的 required 值。

    This 可能会有所帮助。

    【讨论】:

    • 我之前试过这个,这个在顶部添加了额外的收音机,我不想要那个。
    • 我已设置 * @Assert\Choice(choices = {4,3,2,1, null}) 但没有任何改变。
    • OK 我找到了解决方案 'required' => false, 'empty_value' => false
    • @user2156980 不客气。很高兴知道 empty_value 也应该设置为 false。
    【解决方案3】:

    由于 Symfony 3.0 empty_value 已被删除,您需要改用 placeholder

     $builder
            ->add(
                  'student', 
                  'choice', 
                  [
                    'label'=> false,
                    'expanded' => true,
                    'choices' => (Array)new StudentEnum(),
                    'required' => false,
                    'placeholder' => null
                  ]
             );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多