EasyAdminBundle icon indicating copy to clipboard operation
EasyAdminBundle copied to clipboard

Filter autocomplete results

Open blackatze93 opened this issue 9 years ago • 12 comments

If there any way to filter the results of the autocomplete action?

For example I have

image

and I need in that in the autocomplete field only shows the Lugar results that have a boolean property to true:

image

Any idea? (Sorry for my bad english)

blackatze93 avatar May 08 '17 18:05 blackatze93

If there any way to filter the results of the autocomplete action?

Not yet, but likely it would be a nice feature to implement :)

yceruto avatar May 08 '17 19:05 yceruto

However, you can always override the autocompleteAction() and add your custom logic:

    protected function autocompleteAction()
    {
        if ('Lugar' === $this->request->query->get('entity')) {
            $results = // make custom query and see Autocomplete class to know how to parse the results.

            return new JsonResponse($results);
        }

        return parent::autocompleteAction();
    }

yceruto avatar May 08 '17 19:05 yceruto

@javiereguiluz could be nice make public the Autocomplete::processResults() method for these cases, it helps to build the expected result for select2 widget.

yceruto avatar May 08 '17 19:05 yceruto

More and more people are asking this ... so I guess it makes sense. I'm still thinking about it. Thanks!

javiereguiluz avatar May 08 '17 19:05 javiereguiluz

Yeah I've done this by passing an additional argument to autocompleteAction, so my controller:

 protected function autocompleteAction() 
   {
        $results = $this->get('easyadmin.autocomplete')->find(
            $this->request->query->get('entity'),
            $this->request->query->get('query'),
            $this->request->query->get('page', 1),
            'entity.activo = true'
        );

        return new JsonResponse($results);
    }

And overriding the default search action:

// javiereguiluz/easyadmin-bundle/Search/Autocomplete.php

public function find($entity, $query, $page = 1, $dqlFilter = null)
    {
        if (empty($entity) || empty($query)) {
            return array('results' => array());
        }

        $backendConfig = $this->configManager->getBackendConfig();
        if (!isset($backendConfig['entities'][$entity])) {
            throw new \InvalidArgumentException(sprintf('The "entity" argument must contain the name of an entity managed by EasyAdmin ("%s" given).', $entity));
        }

        $paginator = $this->finder->findByAllProperties($backendConfig['entities'][$entity], $query, $page, $backendConfig['show']['max_results'], null, null,  $dqlFilter);

        return array('results' => $this->processResults($paginator->getCurrentPageResults(), $backendConfig['entities'][$entity]));
    }
// javiereguiluz/easyadmin-bundle/Search/Finder.php

public function findByAllProperties(array $entityConfig, $searchQuery, $page = 1, $maxResults = self::MAX_RESULTS, $sortField = null, $sortDirection = null, $dqlFilter = null)
    {
        $queryBuilder = $this->queryBuilder->createSearchQueryBuilder($entityConfig, $searchQuery, $sortField, $sortDirection, $dqlFilter);

        return $this->paginator->createOrmPaginator($queryBuilder, $page, $maxResults);
    }

Is a little long, but it works

blackatze93 avatar May 08 '17 20:05 blackatze93

@blackatze93 great! $dqlFilter should be there in core bundle by default, later we could add this option to EasyAdminAutocompleteType too and use it as query parameter into autocomplete action.

This would make this configuration happy, something like this:

easy_admin:
    entities:
        Product:
            class: AppBundle\Entity\Product
            form:
                fields:
                    - { property: 'category', type: 'easyadmin_autocomplete', type_options: { dql_filter: 'entity.enabled = true' } }
                    # ...
    # ...

yceruto avatar May 08 '17 22:05 yceruto

@yceruto This would be awesome!

blackatze93 avatar May 09 '17 01:05 blackatze93

Would it be possible to filter the autocomplete depending on the entity you are editing ?

erichard avatar Sep 03 '17 14:09 erichard

@erichard No that isn't possible directly. Since you only get the following details from the request object:

?action=autocomplete&entity=YOUR_ENTITY_CLASS&query=YOUR_QUERY

Additionally it's not possible to join before filtering. You can only filter on already joined associations with $dqlFilter.

binarious avatar Dec 03 '17 07:12 binarious

I'm closing this issue because we're starting a new phase in the history of this bundle (see #2059). We've moved it into a new GitHub organization and we need to start from scratch: no past issues, no pending pull requests, etc.

I understand if you are angry or disappointed by this, but we really need to "reset" everything in order to reignite the development of this bundle.

javiereguiluz avatar Feb 24 '18 11:02 javiereguiluz

I know this thread is closed but never found a good solution, mine doesn't use autocomplete, but you can filter the multi-select associated entities. I am still looking for a non-intrusive way to do it for autocomplete.

protected function createEntityFormBuilder($entity, $view)
    {
        $formBuilder = parent::createEntityFormBuilder($entity, $view);
        if (!$this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN')) {
            $user = $this->get('security.token_storage')->getToken()->getUser();
            $promoter = $this->getDoctrine()
                ->getRepository(Promoter::class)
                ->findByUser($user);
            $queryBuilder = $this->getDoctrine()
                ->getRepository(Customer::class)
                ->getActiveByPromoterQueryBuilder($promoter);
            $formBuilder->add(
                'customers', EntityType::class, [
                    'class' => Customer::class,
                    'query_builder' => $queryBuilder,
                    "attr" => ["class" => "form-control select2", "data-widget" => "select2"],
                    'by_reference' => false,
                    'multiple' => true,
                    'required' => false
                ]
            );
        }
        return $formBuilder;
    }

The key is in vendor/easycorp/easyadmin-bundle/src/Resources/views/default/includes/_select2_widget.html.twig. Just add the data-widget attribute to form field.

rernesto avatar Jan 07 '19 17:01 rernesto

Take a look at this proposal https://github.com/EasyCorp/EasyAdminBundle/pull/2598 adding the sort and dql_filter options for autocomplete results, any feedback is welcomed :)

yceruto avatar Feb 07 '19 20:02 yceruto