布尔值和选择符号类型

mlw*_*mos 5 forms choice symfony

使用Symfony框架的选择类型,我们可以确定显示列表,单选按钮或使用这两个键播放的复选框:

'multiple' => false,
'expanded' => true,  //example for radio buttons
Run Code Online (Sandbox Code Playgroud)

假设不是字符串,在“ choices”键中作为数组给出的不同选择的值是布尔值:

$builder->add('myproperty', 'choice', array(
    'choices' => array(
        'Yes' => true,
        'No' => false
     ),
     'label' => 'My Property',
     'required' => true,
     'empty_value' => false,
     'choices_as_values' => true
 )); 
Run Code Online (Sandbox Code Playgroud)

使用列表(选择)显示差异选择是没有问题的,并且当显示表单时,将在列表中选择正确的选择。

如果我添加了之前讨论过的两个键(多重键和扩展键),以单选按钮替换列表,则我的字段没有选定的按钮(尽管它可以与select一起使用)。

有人知道为什么吗?

如何轻松使其工作?

谢谢

注意:实际上,我认为它不能与任何时候一起使用,因为值是布尔值并最终成为字符串,但是由于它适用于列表,所以我想知道为什么它不适用于其他列表。

mlw*_*mos 8

我添加了一个数据转换器;

$builder->add('myproperty', 'choice', array(
    'choices' => array(
        'Yes' => '1',
        'No' => '0'
     ),
     'label' => 'My Property',
     'required' => true,
     'empty_value' => false,
     'choices_as_values' => true
 )); 

 $builder->get('myProperty')
    ->addModelTransformer(new CallbackTransformer(
        function ($property) {
            return (string) $property;
        },
        function ($property) {
            return (bool) $property;
        }
  ));
Run Code Online (Sandbox Code Playgroud)

太神奇了:现在,我已经选中了正确的单选按钮,并在实体中设置了正确的值。

  • 看起来 Symfony 现在可以在不添加 `Transformer` 的情况下处理这种情况:你可以只使用 `'choices' => ['Yes' => true, 'No' => false]`,这非常简单 (2认同)

小智 5

另一个解决方案是使用Doctrine Lifecycle Callbacksphp Type Casting

使用此FormType:

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

//...

$builder->add('active', ChoiceType::class, [
    'choices' => [
        'active' => true,
        'inactive' => false
    ]
])
Run Code Online (Sandbox Code Playgroud)

和实体是这样的:

//...
use Doctrine\ORM\Mapping as ORM;

/**
 * ...
 * @ORM\HasLifecycleCallbacks()                      /!\ Don't forget this!
 * ...
 */
class MyEntity {

    //..

    /**
     * @var bool
     *
     * @ORM\Column(name="active", type="boolean")
     */
    private $active;

    //...

    /**
     * @ORM\PrePersist()
     */
    public function prePersist()
    {
        $this->active = (bool) $this->active; //Force using boolean value of $this->active
    }

    /**
     * @ORM\PreUpdate()
     */
    public function preUpdate()
    {
        $this->active = (bool) $this->active;
    }    

    //...
}
Run Code Online (Sandbox Code Playgroud)