php - 如何将数组的键放入 Symfony 的 ChoiceType 元素中

标签 php symfony twig

我正在尝试构建一个我将在 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_valueschoice_labelchoice_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/

相关文章:

php - 文本和关键字列表之间的亲和性?

php - mysql 从批处理创建索引与 CLI 或 GUI 的比较

php - 使用 FOSRestBundle 和分页器时为 "Resources are not supported in serialized data."

html - 如何在 Twig 文件中添加许可证注释?

php - 按是或否排序

php - 在 CodeIgniter 中,如何使用分页参数从 Controller 调用 ajax url

symfony - Composer 不会安装私有(private)包依赖项

php - FOSRestBundle jsonp请求强制下载

php - 向 Twig 中的对象添加属性

symfony - 在 Twig 中动态调用宏?