Search code examples
formssymfonygroup-byalphabetical

Sort group alphabetically in symfony forms


I'm working with Symfony 3 and I have a little issue for sorting my fields in EntityType. I successfully sorted my choices by the option group_by but the groups are not alphabetically sorted. I have a bunch of object like this. Sorted in groups:

My fields

I would like to sort the groups alphabetically. 'Autres,Fun,Vars,Visuel' Instead of this. Is that even possible?

Thanks by advance!

Edit

Here's the code generating this.
$builder->add('slides' ,
    EntityType::class,array('multiple'=>true,
    'class'=>Slide::class,
    'query_builder'=>function(SlideRepository $er){return $er ->createQueryBuilder('u');},
    'group_by'=>function($value,$key,$index){
                if($value->getGroupe()!=""){
                    return $value->getGroupe();
                }
                else{
                    return "Autres";
                }
            })

Solution

  • Thanks Matteo, that was it. Here's the code which made the job:

    'query_builder'=>function(SlideRepository $er){
        return $er ->createQueryBuilder('u')->orderBy('u.groupe','ASC');}
    

    So, if I use order_by [myField] and then group_by [myField] it will be sorted in groups and alphabetically. Thanks!