Symfony 选择表单内的类型发送键而不是值

Symfony 选择表单内的类型发送键而不是值,symfony,Symfony,我有一个只有两个字段(id和值)的ThemePlace实体 我有一个PlaceType表单,在这个表单中,我想在选择列表中打印所有主题值 这是我的PlaceType中的内容 public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('content') ->add('title') ->add('the

我有一个只有两个字段(id和值)的ThemePlace实体

我有一个PlaceType表单,在这个表单中,我想在选择列表中打印所有主题值

这是我的PlaceType中的内容

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('content')
        ->add('title')
        ->add('theme', ChoiceType::class, [
            'choices' => $options['themes'],
        ])
        ->add('maxUser')
        ->add('longitude')
        ->add('latitude')
        ->add('avatarPath',FileType::class, array('data_class' => null,'required' => false));
}/**
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Place',
        'themes' => 'AppBundle\Entity\ThemePlace'
    ));
}
但在我看来,我得到的是
0/1/2
,而不是
Theme1/Theme2/Theme3

{{ form_widget(form.theme) }}
{{ form_errors(form.theme) }}
我在stack上看到过一些关于在构建器中使用choice_值的话题,但我无法让它工作


谢谢您的帮助。

symfony的选择类型有点不同:

选择数组的结构为:
{displatedvalue}=>{actual value}

(这可能是因为,值通常比字符串复杂得多,而显示值几乎总是字符串——或者至少将它们转换为字符串没有什么坏处。)

我假设您有
[theme1,theme2,theme3]
,它是

[
  0 => theme1, 
  1 => theme2, 
  2 => theme3,
]
如果主题是字符串,则可以将其加倍:

[
  theme1 => theme1,
  theme2 => theme2,
  theme3 => theme3,
]
如果它们是实体,请使用
EntityType
而不是
选项type
()

$builder->add('themes',EntityType::class[
'class'=>Theme::class,//您的类在这里!
“选项”=>$options[“主题”],
'choice_label'=>函数($theme){

return$theme->getName();//我的主题从控制器进入构建器是findAll()的简单结果。因此我没有直接在构建器中构建;这就是为什么我被卡住的原因。@minirok如果它是findAll的结果,请改为使用EntityType:(不过,这扩展了问题)不要忘记实体上的ToStand方法。如果你还有其他问题,考虑打开一个新的问题和/或自己做研究;o)不冒犯,O)
$builder->add('themes', EntityType::class, [
    'class' => Theme::class, // your class here!
    'choices' => $options['themes'],
    'choice_label' => function($theme) { 
         return $theme->getName(); // <-- use your display value
    },
]);