drop-down-menusymfonychoicefield

Combine columns in choice list Symfony form


In my Symfony form I have a choiceType field listing categories. My categorie table looks like this:

id code categorie
1  100  First categorie
2  200  Second categorie
3  210  Second subcategorie

In my form I have a selectfield and with 'choice_label' I can decide which column, either 'code' or 'categorie' to use for the select list. I would like to use both so the user has a selectlist showing:

Is it possible to join the 2 columns for the choice_label; Concatenate the 2 columns in a string just for the purpose of the selectoptions to show? I have tried to find it here and elsewhere. The official docs do not mention this option.


Solution

  • Even in ChoiceType for choice_label you can use callable to set it link

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

    But why do you use ChoiceType for you categories, how do you going to set choices? Why don't you use 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');
        },
    ))