8

How is the best way to add select with choices to filters in Sonata Admin?

For form i can:

$builder->add('gender', 'choice', array(
    'choices'   => array('m' => 'Male', 'f' => 'Female'),
    'required'  => false,
));

but this not working in filters.

makuj
  • 97
  • 1
  • 5

4 Answers4

10

For your admin class you should use configureDatagridFilters function to add your filters,if you want to add custom options for your gender fields you can use doctrine_orm_string and provide your choices list in array form

$datagridMapper
       ->add('gender',
        'doctrine_orm_string',
        array(), 
       'choice',
        array('choices' => array('m' => 'Male', 'f' => 'Female')
        )
    );
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
4

Try this:

protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{

    $datagridMapper

       ->add('gender',null,  array(), ChoiceType::class, array(
           'choices' => array('m' => 'Male', 'f' => 'Female')
       ))
    ;
}
Sebastian Viereck
  • 5,455
  • 53
  • 53
  • Can you highlight which parts make the difference and why they help to solve the problem, such that others can learn from that snippet? – Nico Haase Oct 23 '18 at 08:10
3

On my version - symfony 3.4 and "sonata-project/doctrine-orm-admin-bundle": "^3.0"

worked this way:

->add('preferredLanguage', 'doctrine_orm_choice', [
                    'global_search' => true,
                    'field_type' => ChoiceType::class,
                    'field_options' => [
                        'choices' => [
                            'English' => PotentialCustomerInterface::PREFERRED_LANGUAGE_ENGLISH,
                            'Spanish' => PotentialCustomerInterface::PREFERRED_LANGUAGE_SPANISH
                        ]
                    ]
                ]
            )

The choices are string values in database.

If you want choices from database filtered by some logic:

    ->add('csr', 'doctrine_orm_choice', [
            'field_type' => EntityType::class,

            'field_options' => [
                'class' => User::class,
                'query_builder' => function (UserRepository $userRepository) {
                    return $userRepository->qbFindAdmins();
                },
            ]

        ]
    )

In UserRepository just create method which returns query builder.

Darius.V
  • 737
  • 1
  • 13
  • 29
1

I'm using symfony 4.3 and sonata-admin-bundle 3.0 and this is how I ended up doing:

use Sonata\DoctrineORMAdminBundle\Filter\StringFilter;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

/**
 * @param DatagridMapper $datagridMapper
 */
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper
        ->add('gender', StringFilter::class, ['label' => 'Gender'], ChoiceType::class, [
            'choices' => ['m' => 'Male', 'f' => 'Female']
        ])
    ;
}
Needpoule
  • 4,476
  • 24
  • 33