Search code examples
phpsymfony4formbuilder

FormBuilder how to reverse content of a ChoiceList


Actually I create a ChoiceType (https://symfony.com/doc/current/reference/forms/types/choice.html) from an EntityType and I want to reverse the recovered data.

$formMapper
        ->with('Niveau', ['class' => 'col-md-12'])
        ->add('number', EntityType::class, array('required' => true, 'label' => 'NUMBER',
            'class' => Number::class,
            'choice_label' => 'info',
        ))
        ->end();

example : I get [1, 2, 3, 4, 5] and I want [5, 4, 3, 2, 1] in my ChoiceList.

Is there a way to sort by DESC instead of ASC ? Should I call a request from NumberRepository ?


Solution

  • I think this is what you need in your case:

    $builder->add('users', EntityType::class, array(
        'class' => User::class,
        'query_builder' => function (EntityRepository $er) {
            return $er->createQueryBuilder('u')
                ->orderBy('u.username', 'ASC');
        },
        'choice_label' => 'username',
    ));
    

    https://symfony.com/doc/current/reference/forms/types/entity.html#using-a-custom-query-for-the-entities