Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filter autocomplete results #1629

Closed
blackatze93 opened this issue May 8, 2017 · 12 comments
Closed

Filter autocomplete results #1629

blackatze93 opened this issue May 8, 2017 · 12 comments

Comments

@blackatze93
Copy link

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)

@yceruto
Copy link
Collaborator

yceruto commented May 8, 2017

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
Copy link
Collaborator

yceruto commented May 8, 2017

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
Copy link
Collaborator

yceruto commented May 8, 2017

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

@javiereguiluz
Copy link
Collaborator

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

@blackatze93
Copy link
Author

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

@yceruto
Copy link
Collaborator

yceruto commented May 8, 2017

@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' } }
                    # ...
    # ...

@blackatze93
Copy link
Author

@yceruto This would be awesome!

@erichard
Copy link
Contributor

erichard commented Sep 3, 2017

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

@binarious
Copy link

binarious commented Dec 3, 2017

@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.

@javiereguiluz
Copy link
Collaborator

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.

@rernesto
Copy link

rernesto commented Jan 7, 2019

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.

@yceruto
Copy link
Collaborator

yceruto commented Feb 7, 2019

Take a look at this proposal #2598 adding the sort and dql_filter options for autocomplete results, any feedback is welcomed :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants