You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony 6.1 ChoiceType选项值显示错误问题排查

Symfony 6.1 ChoiceType选项值不符合预期的解决方法

问题出在Symfony ChoiceType对choices数组的默认处理逻辑:当你传入['choice1' => 'value1']这类关联数组时,组件默认会把数组的键(choice1/choice2/choice3)作为<option>的value属性值,数组的值作为默认显示文本。而你需要的是反过来用数组的值做value,用键生成翻译标签,所以需要显式配置choice_value选项。

修改后的表单代码如下:

$builder
  ->add('type', ChoiceType::class, [
    'label' => 'app.security.type',
    'choices' => UserDictionary::POSSIBLE_CHOICES,
    // 指定<option>的value为数组对应的值(value1/value2/value3)
    'choice_value' => function (string $choice, string $key, string $value): string {
        return $value;
    },
    // 用数组的键生成翻译标签(app.choices.choice1等)
    'choice_label' => function (string $choice, string $key, string $value): string {
        return sprintf('app.choices.%s', $key);
    },
  ]);

如果你的项目使用PHP 7.4+,可以用箭头函数简化写法:

$builder
  ->add('type', ChoiceType::class, [
    'label' => 'app.security.type',
    'choices' => UserDictionary::POSSIBLE_CHOICES,
    'choice_value' => fn($choice, $key, $value) => $value,
    'choice_label' => fn($choice, $key, $value) => "app.choices.$key",
  ]);

这样修改后,生成的<option>标签就会符合预期:value属性是value1/value2/value3,显示文本对应app.choices.choice1等翻译键。

内容的提问来源于stack exchange,提问作者PawiX82

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:51:03