ux-autocomplete
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.
Install
npx skills add https://github.com/smnandre/symfony-ux-skills/tree/main/skills/ux-autocomplete
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install smnandre-symfony-ux-skills@llmmart
git clone https://github.com/smnandre/symfony-ux-skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole smnandre/symfony-ux-skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
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
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)
$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
php bin/console make:autocomplete-field # choose "Entity (Doctrine)"
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;
}
}
$builder->add('food', FoodAutocompleteField::class);
Ajax With Any Data Source
php bin/console make:autocomplete-field # choose "Choice (any data source)"
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:
// 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()]],
]);
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 for the full reference, autocompleters, the JSON format and Stimulus values.
Styling
In assets/controllers.json, switch the Tom Select theme:
"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 useextra_options. - Field class not found by the endpoint: the attribute is missing, or
getParent()returns the wrong type. filter_querywithsearchable_fieldsormax_results: incompatible, pick one.- Extending Tom Select from JavaScript does nothing: the extending controller must load eagerly (remove
stimulusFetch: 'lazy') to catchautocomplete:pre-connect. ux_entity_autocompletedeprecation: use theux_autocompleteroute.TypeTestCasefails on theautocompleteoption: registernew AutocompleteChoiceTypeExtension()ingetTypeExtensions().
References
- Symfony UX package page (Markdown summary) ·
symfony/ux-autocompleteon Packagist. - Try the interactive autocomplete demo.
- See how autocomplete works with dependent LiveComponent fields.
- For form fields, Ajax autocompleters and Tom Select integration, see the Symfony UX Autocomplete documentation.
- For
tom_select_optionsand JavaScript plugins, see the Tom Select documentation.
See Also
- stimulus: extend Tom Select through
autocomplete:pre-connectandautocomplete:connect. - live-component: autocomplete fields work inside
ComponentWithFormTraitforms.
Files (symfony-ux-skills)
-
references
-
api.md 9.5 KB
Loading…
-
-
SKILL.md 8.3 KB
--- 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.
Reviews (0)
No reviews yet.
Comments
Sign in to join the conversation.
No comments yet. Start the conversation.