symfonyadminsonata-adminsonatasymfony3

Sonata ODM Admin custom set of filters


I am trying to upgrade my sonata-admin section in project from version 2 to 3. As I understood, the system of filtering had a little bit changed. The section of filtering now is like below:

/**
 * Fields to be shown on filter forms
 *
 * @param DatagridMapper $datagridMapper
 */
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper
        ->add('updated_from', 'doctrine_mongo_callback', [
            'callback' => function ($queryBuilder, $alias, $field, $value) {
                if (!$value['value']) {
                    return;
                }

                $queryBuilder
                    ->field('updated_at')
                    ->gte(new \DateTime($value['value']));

                return true;
            }, 'label' => 'Updated at, from'])
        ->add('updated_to', 'doctrine_mongo_callback', [
            'callback' => function ($queryBuilder, $alias, $field, $value) {
                if (!$value['value']) {
                    return;
                }

                $queryBuilder
                    ->field('updated_at')
                    ->lte(new \DateTime($value['value']));

                return true;
            }, 'label' => 'Updated at, to'])
        ->add('role', 'doctrine_mongo_choice', [], ChoiceType::class, [
            'label' => 'Role Name',
            'operator_type' => HiddenType::class,

            'field_options' => [
                'choices' => $this->getFilter('role')
            ]
        ]);
 }

Generally filters work, but I can not use only one filter separately. When I am trying to filter by "updated_from" sonata ask me to choose other 2 filters and show me nothing. Then I choose those other 2 filters and everything work.

Can somebody help in this question? Thank you.


Solution

  • After investigation in this question, I came to decision.

    When we set the second parameter at "add" method, sonata identify the filter type as "DefaultFilterType". Then Sonata assigns some default parameters to that filter. It influenced to the filter behavior. But if I leave second parameter as "null", then filter will be looking for a type of "FieldType" (4th parameter). Then filter become a "ChoiceType" in my case and it works fine.

    And one more important stuff, that "ChoiceType" should be from Symfony, not from Sonata.