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.
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')
)
);
Try this:
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('gender',null, array(), ChoiceType::class, array(
'choices' => array('m' => 'Male', 'f' => 'Female')
))
;
}
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.
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']
])
;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With