Sonata admin, custom query in filter

12,047

Filters configuration is quite different than form configuration in sonata admin bundle.

Look at documentation: http://sonata-project.org/bundles/doctrine-orm-admin/master/doc/reference/filter_field_definition.html

When you add new filter through configuratDataFilters it receives parameters: field name, filter type, filter configuration, form field type and form field configuration.

So if you want only to override query_buider for entity choice type you should try call like this:

->add('commercial', null, array(), 'entity', array(
          'class' => 'MyBundle:User',
          'query_builder' => function(EntityRepository $er) {
               return $er->createQueryBuilder('u')
                         ->groupBy('u.id')
                         ->orderBy('u.id', 'ASC')
                         ->setParameters(array(1 => 'Commercial'));
           }
))
Share:
12,047
Clément Andraud
Author by

Clément Andraud

I'm a wonderful dev !

Updated on June 25, 2022

Comments

  • Clément Andraud
    Clément Andraud almost 2 years

    I'm using SonataAdminBundle and I have a question about filters in the class MyEntityAdmin.

    I have a first function protected function configureFormFields(FormMapper $formMapper) for list all fields to be shown on create/edit forms.

    If I have a field type entity, I can do something like this:

    ->add('commercial', 'entity', array(
                    'class' => 'MyBundle:User',
                    'query_builder' => function(EntityRepository $er) {
                      return $er->createQueryBuilder('u')
                                ->groupBy('u.id')
                                ->orderBy('u.id', 'ASC')
                                ->setParameters(array(1 => 'Commercial'));
                  },)
                )
    

    But I have another function protected function configureDatagridFilters(DatagridMapper $datagridMapper) for Fields to be shown on filter forms, and I have do to the same thing, a custom query on an entity field type, but if I do the same, I have the error:

    No attached service to type named `entity`  
    

    How can I do that ?