如何在Sonata Admin中添加带选项的选择到过滤器的最佳方式


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

如何在Sonata Admin中为过滤器添加带选项的选择?

对于表格,我可以:

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

但这在过滤器中不起作用。

对于您的管理类,您应该使用configureDatagridFilters函数来添加过滤器,如果您想为gender字段添加自定义选项,您可以使用doctrine_orm_string并以数组形式提供您的选择列表

$datagridMapper
       ->add('gender',
        'doctrine_orm_string',
        array(), 
       'choice',
        array('choices' => array('m' => 'Male', 'f' => 'Female')
        )
    );

试试这个:

protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper
       ->add('gender',null,  array(), ChoiceType::class, array(
           'choices' => array('m' => 'Male', 'f' => 'Female')
       ))
    ;
}

在我的版本-symfony 3.4和"sonata项目/条令orm管理捆绑包"上:"^3.0"

工作方式:

->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
                        ]
                    ]
                ]
            )

这些选项是数据库中的字符串值。

如果你想从数据库中选择一些逻辑过滤:

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

在UserRepository中,只需创建返回查询生成器的方法。

我正在使用symfony 4.3sonata管理捆绑包3.0,这就是我最终的做法:

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']
        ])
    ;
}