Symfony 表单 ChoiceType 只有值

Symfony form ChoiceType with only values

Symfony documentation 说您应该像这样使用 use ChoiceType:

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

$builder->add('isAttending', ChoiceType::class, array(
    'choices'  => array(
        'Maybe' => null,
        'Yes' => true,
        'No' => false,
    ),
));

但是,由于我的值非常简单,可以像键一样工作,所以我想做这样的事情:

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

$builder->add('titre', ChoiceType::class, array(
    'choice_value'  => array(
        'Pr', 'Dr', 'Mr', 'Mrs'
    ),
))

我怎样才能做到这一点?

如果我不能,背后的充分理由是什么?

您可以尝试使用 array_combine:

创建相同的 key/value 数组
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

$choices = array('Pr', 'Dr', 'Mr', 'Mrs');

$builder->add('isAttending', ChoiceType::class, array(
    'choices'  => array_combine($choices, $choices),
));

A Symfony-ish way:

$builder->add('isAttending', ChoiceType::class, array(
    'choices' => array('Pr', 'Dr', 'Mr', 'Mrs'),
    'choice_label' => function ($value) { return $value; },
));