9

I'm using the symfony forms for creating a select-box with all my users. I display them by fullname, but want to sort them alphabetically.

$builder->add('transferTo', 'document', [
        'class' => 'UserBundle:User',
        'property' => 'fullname',
        'label'  => 'Overdragen aan',
        'attr' => ['class' => 'form-control selectpicker'],
        'label_attr' => ['class' => 'col-sm-2 control-label'],
        'multiple'  => false,
        'required' => true
    ]);

How can i sort the users alphabetically on fullname of firstName?

2
  • Can show a snapshot of the output and the one you want? Commented Mar 17, 2014 at 20:27
  • It outputs a regular select with a few options (fullnames). But i want those names sorted alphabetically. Commented Mar 17, 2014 at 20:30

1 Answer 1

23

What you need is to add queryBuilder to the form params

use Doctrine\ORM\EntityRepository;

$builder->add('transferTo', 'document', [
    'class' => 'UserBundle:User',
    'query_builder' => function(EntityRepository $repository) { 
            return $repository->createQueryBuilder('u')->orderBy('u.fullname', 'ASC');
        }
    'property' => 'fullname',
    'label'  => 'Overdragen aan',
    'attr' => ['class' => 'form-control selectpicker'],
    'label_attr' => ['class' => 'col-sm-2 control-label'],
    'multiple'  => false,
    'required' => true
]);

I assumed the fieldname in your entity is u.fullname

Sign up to request clarification or add additional context in comments.

7 Comments

No errors but my select box isn't ordered either. (ASC nor DESC works)
Using ODM (MongoDB) use Doctrine\ODM\MongoDB\DocumentRepository; 'query_builder' => function(DocumentRepository $repository) { return $repository->createQueryBuilder('u')->sort('u.firstName', 'desc'); }, But still not sorting
Are you using MongoDB?
Yes i'm using MongoDB. I used sort instead of orderBy, used "document" instead of "entity" and Use DocumentRepository instead of EntityRepository. My select box isn't sorted but there aren't errors either.
I know the solution is adding the queryBuilder to form builder params either it's Doctrine or MongoDB; If you could find it it will help you
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.