使用ChoiceType与整数作为选择值

4
在Symfony 2.8上遇到了一个小问题。我有几个数据库字段,其中一个是整数,另一个是小数。当我构建表单时,这些字段是下拉菜单,因此我使用ChoiceType而不是IntegerType或NumberType。
事实上,表单运作正常,两者之间的内部区别显然没有问题,我可以选择一个值并将其正确地保存到数据库中。
现在的问题出现在Listener中。当某些字段更改时,我需要启动一个额外的过程,因此我使用事件侦听器并使用getEntityChangeSet()命令。
我注意到它报告这些字段已更改,因为它识别1000和"1000"之间的差异,我可以在Vardump输出中看到。
 "baths" => array:2 [▼
    0 => 1.5
    1 => "1.5"
  ]

这会导致监听器始终触发我的钩子,即使值实际上没有改变。如果我将表单类型更改为Integer,那只是一个文本输入,并且我失去了下拉列表。如何强制下拉选择类型将数字视为数字?

在我的实体中,这是正确定义的:

 /**
 * @var float
 *
 * @ORM\Column(name="baths", type="decimal", precision=10, scale=1, nullable=true)
 */
private $baths;

在我的常规表单中:

 ->add('baths', BathsType::class)

它会拉取以下内容:

class BathsType extends AbstractType
{


    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'choices' => array_combine(range(1,10,0.5),range(1,10,0.5)),
            'label' => 'Bathrooms:',
            'required' => false,
            'placeholder' => 'N/A',
            'choices_as_values' => true,

        ]);
    }

    public function getParent()
    {
        return 'Symfony\Component\Form\Extension\Core\Type\ChoiceType';
    }


}
2个回答

5

您应该仅向choices选项传递值,它们将由用作“隐藏”HTML输入值的字符串的数字键索引,这些键将在背后进行映射。

然后使用choice_label将标签(可见值)设置为强制转换为字符串的选项:

class BathsType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'choices' => range(1,10,0.5),
            'label' => 'Bathrooms:',
            'required' => false,
            'placeholder' => 'N/A',
            'choices_as_values' => true,
            'choice_label' => function ($choice) {
                return $choice;
            },
        ]);
    }

    public function getParent()
    {
        return 'Symfony\Component\Form\Extension\Core\Type\ChoiceType';
    }
}

1
在Symfony 4中,choices_as_values不存在,因此解决方案与Heah answer相同,但不包括该选项。
class BathsType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'choices' => range(1,10,0.5),
            'label' => 'Bathrooms:',
            'required' => false,
            'placeholder' => 'N/A',
            'choice_label' => function ($choice) {
                return $choice;
            },
        ]);
    }

    public function getParent()
    {
        return 'Symfony\Component\Form\Extension\Core\Type\ChoiceType';
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接