我正在尝试构建一个我将在 Twig 模板中实现的表单。为此,我使用了一些 HTML 元素。其中之一是来自 Symfony 组件的 ChoiceType。我创建了一个传递给 add
方法的数组。
我的愿望是在 value 属性中显示键,在标签中显示数组的每个值,我没有做到这一点
protected $lsa_types = array(
'B' => 'Boolean',
'D' => 'Date',
'F' => 'Float',
'I' => 'Integer',
'L' => 'List',
'S' => 'String',
'T' => 'Text',
);
$form->add('type', ChoiceType::class, array('choices' => $this->lsa_types,
'choice_label' => function ($value) {
return $value;
},
'choice_value' => function ($key) {
return $key;
},
'required' => true));
最佳答案
按照@Massimiliano 的评论进行操作,但省略choices_as_values
、choice_label
和choice_value
选项:
protected $lsa_types = array(
'B' => 'Boolean',
'D' => 'Date',
'F' => 'Float',
'I' => 'Integer',
'L' => 'List',
'S' => 'String',
'T' => 'Text',
);
...
$choices = array_flip($this->lsa_types);
$form
->add(
'type',
ChoiceType::class,
array(
'choices' => $choices,
'required' => true
)
)
;
关于php - 如何将数组的键放入 Symfony 的 ChoiceType 元素中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45935965/