Skip to content

[AutoComplete] "preferred_choices" are ignored #2257

Open
@jmfeurprier

Description

@jmfeurprier

I recently switched from regular "EntityType" form fields to "BaseEntityAutocompleteType", and most features work as expected, except for preferred choices, which appear to be totally ignored.

Given this form + this field :

<?php

namespace App\Form;

use App\Entity\Individual;
use App\Repository\BookmarkRepository;
use Override;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\UX\Autocomplete\Form\AsEntityAutocompleteField;

#[AsEntityAutocompleteField]
class AutocompleteTestType extends AbstractType
{
    public function __construct(
        private readonly BookmarkRepository $bookmarkRepository,
    ) {
    }

    #[Override]
    public function buildForm(
        FormBuilderInterface $builder,
        array $options,
    ): void {
        $builder
            ->setMethod('GET')
            ->add(
                'test',
                AutocompleteTestField::class,
                [
                    'preferred_choices' => $this->getPreferredChoices(),
                ],
            )
            ->add(
                'submit',
                SubmitType::class,
            )
        ;
    }

    /**
     * @return Individual[]
     */
    private function getPreferredChoices(): iterable
    {
        $individuals = [];

        foreach ($this->bookmarkRepository->findAll() as $bookmark) {
            $individuals[] = $bookmark->getIndividual();
        }

        return $individuals;
    }
}
<?php

namespace App\Form;

use App\Entity\Individual;
use Override;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\UX\Autocomplete\Form\AsEntityAutocompleteField;
use Symfony\UX\Autocomplete\Form\BaseEntityAutocompleteType;

#[AsEntityAutocompleteField]
class AutocompleteTestField extends AbstractType
{
    #[Override]
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(
            [
                'autocomplete' => true,
                'choice_label' => static fn(Individual $individual) => "{$individual->getLastName()}, {$individual->getFirstName()}",
                'choice_value' => 'id',
                'class'        => Individual::class,
                'multiple'     => false,
            ]
        );
    }

    #[Override]
    public function getParent(): string
    {
        return BaseEntityAutocompleteType::class;
    }
}

Expected behavior

Having the preferred choices showing before the autocomplete-fetched choices, like for non-autocomplete fields (EntityType, ChoiceType, etc).
...Or having the documentation reflect the absence of support for this feature.

Actual behavior

Starting with an empty selection, when I click on the form drop-down, the list is empty, the spinner shows, then the list of all choices is displayed, instead of showing preferred choices first, then the other choices.

image

Activity

jmfeurprier

jmfeurprier commented on Oct 11, 2024

@jmfeurprier
Author

Thanks for the documentation link.

I adapted the code to be using the extra_options, but the preferred choices are still ignored :

<?php

namespace App\Form;

use App\Repository\BookmarkRepository;
use Override;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\UX\Autocomplete\Form\AsEntityAutocompleteField;

#[AsEntityAutocompleteField]
class AutocompleteTestType extends AbstractType
{
    public function __construct(
        private readonly BookmarkRepository $bookmarkRepository,
    ) {
    }

    #[Override]
    public function buildForm(
        FormBuilderInterface $builder,
        array $options,
    ): void {
        $builder
            ->setMethod('GET')
            ->add(
                'test',
                AutocompleteTestField::class,
                [
                    'extra_options' => [
                        'preferred_choices' => $this->getPreferredChoices(),
                    ],
                ],
            )
            ->add(
                'submit',
                SubmitType::class,
            )
        ;
    }

    /**
     * @return string[]
     */
    private function getPreferredChoices(): iterable
    {
        $individuals = [];

        foreach ($this->bookmarkRepository->findAll() as $bookmark) {
            $individuals[] = $bookmark->getIndividual()->getId();
        }

        return $individuals;
    }
}
<?php

namespace App\Form;

use App\Entity\Individual;
use App\Repository\IndividualRepository;
use Override;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\UX\Autocomplete\Form\AsEntityAutocompleteField;
use Symfony\UX\Autocomplete\Form\BaseEntityAutocompleteType;

#[AsEntityAutocompleteField]
class AutocompleteTestField extends AbstractType
{
    public function __construct(
        private readonly IndividualRepository $individualRepository,
    ) {
    }

    #[Override]
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(
            [
                'autocomplete'      => true,
                'choice_label'      => static fn(Individual $individual) => "{$individual->getLastName()}, {$individual->getFirstName()}",
                'choice_value'      => 'id',
                'class'             => Individual::class,
                'preferred_choices' => $this->getPreferredChoices(...),
            ]
        );
    }

    /**
     * @return Individual[]
     */
    private function getPreferredChoices(Options $options): iterable
    {
        $ids = $options['extra_options']['preferred_choices'] ?? [];

        if (empty($ids)) {
            return [];
        }

        return $this->individualRepository->findBy(
            [
                'id' => $ids,
            ]
        );
    }

    #[Override]
    public function getParent(): string
    {
        return BaseEntityAutocompleteType::class;
    }
}
carsonbot

carsonbot commented on Apr 12, 2025

@carsonbot

Thank you for this issue.
There has not been a lot of activity here for a while. Has this been resolved?

jmfeurprier

jmfeurprier commented on Apr 12, 2025

@jmfeurprier
Author

No resolution so far.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @smnandre@jmfeurprier@carsonbot

        Issue actions

          [AutoComplete] "preferred_choices" are ignored · Issue #2257 · symfony/ux