在选择列表Symfony表单中组合列

zef*_*zef 2 choicefield symfony drop-down-menu

在我的Symfony表单中,我有一个choiceType字段列出类别.我的分类表如下所示:

id code categorie
1  100  First categorie
2  200  Second categorie
3  210  Second subcategorie
Run Code Online (Sandbox Code Playgroud)

在我的表单中,我有一个selectfield和'choice_label',我可以决定使用哪个列,'code'或'categorie'用于选择列表.我想同时使用这两个,所以用户有一个选择列表显示:

  • 100第一类
  • 200第二类
  • 等等

是否可以为choice_label加入2列; 连接字符串中的2列只是为了显示选择选项的目的?我试图在这里和其他地方找到它.官方文档没有提到这个选项.

Den*_*mov 9

即使在ChoiceType for choice_label中,您也可以使用callable来设置它的链接

'choice_label' => function($category, $key, $index) {
    /** @var Category $category */
    return $category->getId() . ' ' . $category->getName();
},
Run Code Online (Sandbox Code Playgroud)

但是为什么你会为你的类别使用ChoiceType,你如何设置选择?你为什么不使用EntityType?

->add('category', EntityType::class, array(
    'choice_label' => function ($category) {
        return $category->getId() . ' ' . $category->getName();
    },
    'class' => 'AppBundle:Category',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('c')
            ->orderBy('c.id', 'ASC');
    },
))
Run Code Online (Sandbox Code Playgroud)