【问题标题】:How can I put the keys of an array in a ChoiceType element for Symfony如何将数组的键放在 Symfony 的 ChoiceType 元素中
【发布时间】:2017-08-29 09:53:33
【问题描述】:

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

【问题讨论】:

  • 这里的问题是你没有$value | $key 从您试图传递给闭包的数组中,您可能希望重新处理您的数组,使其看起来像 $array = [ ["key"=>"B", "value"=>"Boolean "], ["key"=>"D", "value"=>"Date"],... ];然后你可以传递给闭包,比如 ... "choice_label" => function($data) {return $data['value']; } 等等
  • 尝试翻转您的阵列并使用"choices_as_values" => true 作为您的 ChoiceType 的选项
  • choices_as_values 从 symfony 的第三个版本开始被弃用

标签: php symfony twig


【解决方案1】:

按照@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
        )
    )
;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多