Skip to content
Back to skills

Ux Autocomplete

ASecurity

Symfony UX Autocomplete: searchable selects and Ajax suggestions for large Symfony form lists. Use for EntityType, ChoiceType, Tom Select, the autocomplete option, #[AsEntityAutocompleteField], #[AsAutocompleteField], AutocompleterInterface, extra_options and tom_select_options.

  • 191 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 2, 2026
ai-agentsjavascriptrustgojavaphpbashapisecuritydocumentation

Works with

  • api

Security analysis

A92/100
  • mediumInstalls packages at runtime which could introduce malicious dependencies

Pro scans all 2 files and shows the line behind each finding

Scanned December 2, 2026

npx -y skills add smnandre/symfony-ux-skills --skill ux-autocomplete --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Ux Autocomplete?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Ux Autocomplete
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/smnandre-ux-autocomplete/badge)](https://www.skillsdirectory.com/skills/smnandre-ux-autocomplete)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: ux-autocomplete
description: 'Symfony UX Autocomplete: searchable selects and Ajax suggestions for large Symfony form lists. Use for EntityType, ChoiceType, Tom Select, the autocomplete option, #[AsEntityAutocompleteField], #[AsAutocompleteField], AutocompleterInterface, extra_options and tom_select_options.'
license: MIT
metadata:
  author: Simon André
  url: https://smnandre.dev
---

# UX Autocomplete

Turn any `ChoiceType`, `EntityType`, `EnumType`, `TextType` or plain `<select>` into a searchable control powered by Tom Select. Options are filtered in the browser, or loaded through Ajax from Doctrine or any other data source.

## Installation

```bash
composer require symfony/ux-autocomplete
```

Requires StimulusBundle. With Encore: `npm install --force`, then restart `npm run watch`.

## Choose the Mode

| Situation | Mode | How |
|-----------|------|-----|
| A few dozen options | Local | `'autocomplete' => true` on the field |
| Many Doctrine entities | Ajax, entity | Field class with `#[AsEntityAutocompleteField]`, parent `BaseEntityAutocompleteType` |
| API, search index, enum, array | Ajax, any source | Field class with `#[AsAutocompleteField]`, parent `AutocompleteChoiceType` |
| No Symfony Form | Ajax endpoint | `AutocompleterInterface` service + Stimulus controller |
| Free tags | Create items | `TextType` with `'autocomplete' => true` and `create` |

Since Symfony UX 3.5+, the package works with any data source: `#[AsAutocompleteField]`, `AutocompleteChoiceType`, `AutocompleterInterface`, the `ux_autocomplete` route and `max_options`.

## Local (All Options in the Page)

```php
$builder
    ->add('food', EntityType::class, [
        'class' => Food::class,
        'placeholder' => 'What should we eat?',
        'autocomplete' => true,
    ])
    ->add('portionSize', ChoiceType::class, [
        'choices' => ['small' => 's', 'medium' => 'm', 'large' => 'l'],
        'autocomplete' => true,
    ]);
```

## Ajax With Doctrine

```bash
php bin/console make:autocomplete-field   # choose "Entity (Doctrine)"
```

```php
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\UX\Autocomplete\Form\AsEntityAutocompleteField;
use Symfony\UX\Autocomplete\Form\BaseEntityAutocompleteType;

#[AsEntityAutocompleteField]
final class FoodAutocompleteField extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'class' => Food::class,
            'placeholder' => 'What should we eat?',
            'searchable_fields' => ['name', 'category.name'],   // all fields when null
            'security' => 'ROLE_USER',                          // endpoint is public otherwise
        ]);
    }

    public function getParent(): string
    {
        return BaseEntityAutocompleteType::class;
    }
}
```

```php
$builder->add('food', FoodAutocompleteField::class);
```

## Ajax With Any Data Source

```bash
php bin/console make:autocomplete-field   # choose "Choice (any data source)"
```

```php
use Symfony\UX\Autocomplete\Form\AsAutocompleteField;
use Symfony\UX\Autocomplete\Form\AutocompleteChoiceType;

#[AsAutocompleteField]
final class CountryAutocompleteField extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'choices' => ['France' => 'FR', 'Germany' => 'DE', 'United Kingdom' => 'GB'],
            'placeholder' => 'Choose a country',
        ]);
    }

    public function getParent(): string
    {
        return AutocompleteChoiceType::class;
    }
}
```

Any `ChoiceType` option works; choices are filtered and paginated by the endpoint.

## The Golden Rule: Options Live in the Field Class

The Ajax endpoint rebuilds the field from its class alone. Options passed to `->add()` exist on the first render only:

```php
// WRONG: ignored during the Ajax search
$builder->add('food', FoodAutocompleteField::class, [
    'query_builder' => fn (EntityRepository $er) => $er->createQueryBuilder('f')->andWhere('f.id != :id'),
]);

// RIGHT: pass scalar data as extra_options, read it in the field class
$builder->add('food', FoodAutocompleteField::class, [
    'extra_options' => ['excluded_foods' => [$currentFood->getId()]],
]);
```

```php
use Symfony\Component\OptionsResolver\Options;

$resolver->setDefaults([
    'class' => Food::class,
    'query_builder' => function (Options $options) {
        return function (EntityRepository $er) use ($options) {
            $qb = $er->createQueryBuilder('o');
            $excluded = $options['extra_options']['excluded_foods'] ?? [];
            if ([] !== $excluded) {
                $qb->andWhere($qb->expr()->notIn('o.id', $excluded));
            }

            return $qb;
        };
    },
]);
```

`extra_options` only carries scalars, `null` and arrays of those. They travel in the URL, protected against tampering by a checksum.

## Main Options

| Option | Default | Applies to |
|--------|---------|------------|
| `autocomplete` | `false` | Any choice or text field |
| `tom_select_options` | `[]` | Any; Tom Select settings, including `plugins` |
| `options_as_html` | `false` | Any; labels are escaped unless enabled |
| `max_options` | `null` (50 for Ajax) | Options displayed at once |
| `min_characters` | `3` | Ajax fields |
| `max_results` | `10` | Results per page returned by the endpoint |
| `preload` | `focus` | Ajax fields: `focus`, `true` or `false` |
| `searchable_fields` | `null` (all) | Entity fields; relations allowed (`category.name`) |
| `filter_query` | `null` | Entity fields; full control of the search, replaces `searchable_fields` and `max_results` |
| `security` | `false` | Ajax fields: a role or a callable |
| `extra_options` | `[]` | Ajax fields |
| `preferred_choices` | | Since 3.7: listed first in Ajax results; entities only for entity fields |

Texts (`loading_more_text`, `no_results_found_text`, `no_more_results_text`) are translated in the `AutocompleteBundle` domain. See [references/api.md](references/api.md) for the full reference, autocompleters, the JSON format and Stimulus values.

## Styling

In `assets/controllers.json`, switch the Tom Select theme:

```json
"autoimport": {
    "tom-select/dist/css/tom-select.default.css": false,
    "tom-select/dist/css/tom-select.bootstrap5.css": true
}
```

## Key Principles

**Local first, Ajax when the list is large.** Local mode works with the field option alone.

**Secure every Ajax field that exposes private data.** The endpoint is public by default; set `security`, or move it under a firewall with a custom route.

**Configure in the class, vary with `extra_options`.**

**Keep `options_as_html` off unless labels are trusted HTML.** Labels are escaped to prevent XSS.

## Gotchas

- **Search ignores my `query_builder` / `choices` / `preferred_choices`**: they were passed to `->add()`. Move them into the field class or use `extra_options`.
- **Field class not found by the endpoint**: the attribute is missing, or `getParent()` returns the wrong type.
- **`filter_query` with `searchable_fields` or `max_results`**: incompatible, pick one.
- **Extending Tom Select from JavaScript does nothing**: the extending controller must load eagerly (remove `stimulusFetch: 'lazy'`) to catch `autocomplete:pre-connect`.
- **`ux_entity_autocomplete` deprecation**: use the `ux_autocomplete` route.
- **`TypeTestCase` fails on the `autocomplete` option**: register `new AutocompleteChoiceTypeExtension()` in `getTypeExtensions()`.

## References

- [Symfony UX package page](https://ux.symfony.com/autocomplete) ([Markdown summary](https://ux.symfony.com/autocomplete.md)) · [`symfony/ux-autocomplete` on Packagist](https://packagist.org/packages/symfony/ux-autocomplete).
- Try the [interactive autocomplete demo](https://ux.symfony.com/autocomplete#demo).
- See how [autocomplete works with dependent LiveComponent fields](https://ux.symfony.com/demos/live-component/dependent-form-fields).
- For form fields, Ajax autocompleters and Tom Select integration, see the [Symfony UX Autocomplete documentation](https://symfony.com/bundles/ux-autocomplete).
- For `tom_select_options` and JavaScript plugins, see the [Tom Select documentation](https://tom-select.js.org/docs/).

## See Also

- **stimulus**: extend Tom Select through `autocomplete:pre-connect` and `autocomplete:connect`.
- **live-component**: autocomplete fields work inside `ComponentWithFormTrait` forms.

Files in this skill

  • SKILL.md8.3 KB
  • references/api.md9.5 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.