How can I use the querybuilder with choice label in formbuilder?

Viewed 146

I am using the formbuilder querybuilder with choice label:

 $options['query_builder'] = function (EntityRepository $er) use ($fieldId) {
        $output = $er->createQueryBuilder('c')
        ->orderBy('c.name', 'ASC');
        return $output;
 };

 $options['choice_label'] = 'category';

It works very well, also when I try to get the name instead:

 $options['choice_label'] = 'name';

But what I would need is a combination of both in my dropdown, but still keep the ordering.

   $options['choice_label'] = 'category -> name';

I cannot figure out how to do that. I am grateful for any advice.

1 Answers

'choice_label' can also be used with a function (docs).

'choice_label' => function (Category $category) {
    return $category->getId() . ' -> ' . $category->getName();
}

to order the results by category name this should work:

'query_builder' => function (EntityRepository $er) use ($fieldId) {
    $output = $er->createQueryBuilder('c')
        ->join('c.category', 'ca')
        ->orderBy('ca.name', 'ASC')
        ->addOrderBy('c.name', 'ASC');
    return $output;
 };
Related