0

I have this form :

$builder
    ->add('restaurantsFilter1', 'entity', [
        'label'       => 'Commune',
        'empty_value' => 'Dans toute la Narbonnaise',
        'class'       => 'AppBundle:City',
        'choice_label'    => 'name',
        'query_builder' => function (EntityRepository $er) {
            return $er
                ->createQueryBuilder('c')
                ->addSelect('d')
                ->leftJoin('c.documents', 'd')
                ->where('d.type = :type')
                ->orderBy('c.name')
                ->setParameter('type', Document::T_VILLAGE)
            ;
        },
    ])

which is a select which displays a list of cities.

A client told me that he needed a field "Around me" which will display all cities around 20 km.

So to do so, I created a new city in my database with this name, but now I need to put it in the first position of my select.

In sql I would use something like ORDER BY (insee_code= '[specific_code_of_the_city]') but I dont know how I could that with the query builder.

Do you have an idea how I could do that with the symfony query builder ?

EDIT: That's the exact issue that How do I return rows with a specific value first?

Community
  • 1
  • 1
Dimitri Danilov
  • 1,338
  • 1
  • 17
  • 45

1 Answers1

1

You could create a hidden field and order by that.

return $er
    ->createQueryBuilder('c')
    ->addSelect('CASE
                     WHEN c.name = "specific_code_of_city"
                     THEN 0
                     ELSE 1
                 END as HIDDEN presetOrder')
    ->addSelect('d')
    ->leftJoin('c.documents', 'd')
    ->where('d.type = :type')
    ->orderBy('presetOrder', 'ASC')
    ->addOrderBy('c.name', 'ASC')
    ->setParameter('type', Document::T_VILLAGE)
;
qooplmao
  • 17,622
  • 2
  • 44
  • 69