Searchable select with Tom Select
uiTomSelect(config) adds searchable single and multiple selection to Ātrium forms. It loads the pinned Tom Select engine and stylesheet on demand, follows the application theme, and exposes an Alpine model. The showcase route /components/tom-select demonstrates selection, removable multi-select items, local and asynchronous item creation, HTTP loading with retry, and grouped or disabled options.
Integrate a field
createAdmin registers uiTomSelect. Define settings in your application-owned page provider, then include the shared partial. The provider is also exported as tomSelect from @agon/atrium and @agon/atrium/components/tom-select for composition with extendComponent.
/** * Register the application form when its route loads. * * @param {object} context - Lazy page dependencies. * @param {object} context.Alpine - Shared Alpine runtime. * @returns {void} Registers a form with a parent-owned selection. */export function register({ Alpine }) { Alpine.data('projectForm', /** * Create a fresh form model and field settings. * * @returns {object} Application form state. */ () => ({ technology: 'alpine', technologyField: { label: 'Technology', name: 'technology', required: true, options: { options: [ { value: 'alpine', text: 'Alpine.js' }, { value: 'vite', text: 'Vite' } ] } } }) );}<section x-data="projectForm"> <div x-data="uiTomSelect(technologyField)" x-modelable="value" x-model="technology"> <include src="ui:tom-select.html"></include> </div></section>Give each field a visible label or translated labelKey. The partial creates unique IDs and associates the generated combobox with its label and request feedback. Arrow keys navigate results, Enter selects or creates an item, Escape closes the menu, and Backspace removes a selected item. required participates in native form validation and name supplies ordinary form data. A multiple field submits repeated values with the same name.
Settings and model
| Setting | Default | Contract |
|---|---|---|
value | '', or [] for multiple selection | Initial string identifier or array of string identifiers. x-modelable="value" connects a parent-owned model. |
multiple | false | Enables multiple selection and an array model. |
label, labelKey | '', tomSelectLabel | Plain-text label or translation key. |
name, required | '', false | Native form submission and validation. |
disabled | false | Initial state. Updating the provider’s disabled property also updates native controls. |
options | {} | Tom Select options, option groups, plugins, creation rules, maximum items, search fields, and custom option/item rendering. |
load | Unset | Async function receiving { query, signal } and resolving an array of option records. |
minQueryLength | 2 | Minimum trimmed input length before remote search. |
create | Unset | Async function receiving { input, signal } and resolving one saved option record. |
Use options.options for records with { value, text }. Custom records can use options.valueField, options.labelField, and options.searchField. Preselected identifiers must already have matching records, including remote selections. Supply those records in options.options. Parent model updates select existing records silently. Changing an unknown identifier does not fetch or invent its label. Clear or reset forms by updating their parent models. Do not rely on native form.reset() to synchronize Alpine state.
The wrapper owns items, mode, single-select maxItems, dropdownParent, controlInput, preload, refreshThrottle, onChange, onType, shouldLoad, and load. Configure remote loading through config.load, not options.load. Remote fields disable local search ranking because the adapter returns the matching results. Tom Select’s loadThrottle defaults to 300 milliseconds and can be configured through options. The dropdown stays inside the field, so place it in a container that permits overflow.
The shared empty, loading, minimum-query, and creation renderers are localized and reserved. options.render.option and options.render.item remain available. Return DOM nodes using textContent, or escape every external string with the supplied Tom Select escape function. Never return unescaped server HTML. Settings are captured at construction. Recreate the Alpine field to change its schema, multiplicity, or adapters.
Multiple selection and local creation
const tagField = { label: 'Tags', multiple: true, options: { maxItems: 5, create: true, persist: false, plugins: ['remove_button'], options: [{ value: 'design', text: 'Design' }] }};The model is an array. Multiple fields enable the remove_button plugin by default. An explicit options.plugins value replaces the default plugins. All plugins in Tom Select’s complete build are available. Local create: true uses the typed label as the identifier. With persist: false, a user-created option disappears when deselected. Creation does not persist data to a backend.
Use options.optgroups with { value, label } records and each option’s optgroup property to group results. An option with disabled: true cannot be selected. The showcase includes accent-insensitive local searching and a three-item selection limit.
Remote data loading
The application owns HTTP transport, authorization, response normalization, and server-side filtering. For example, create the field settings in the page controller using your adapter:
const contactField = { label: 'Contacts', multiple: true, minQueryLength: 2, options: { valueField: 'id', labelField: 'name' }, /** * Fetch authorized contact options for the current query. * * @param {object} request - Search context. * @param {string} request.query - User-entered query. * @param {AbortSignal} request.signal - Cancellation signal. * @returns {Promise<Array<object>>} Normalized contact options. * @throws {Error} When the backend rejects the request. */ async load({ query, signal }) { const response = await fetch(`/api/contacts?q=${encodeURIComponent(query)}`, { signal }); if (!response.ok) { throw new Error('Contact search failed.'); } const payload = await response.json(); return payload.items; }};A new query cancels the previous request and removes obsolete unselected options. Selected records remain available. Results from an aborted request are rejected even when an adapter ignores cancellation. Empty results and failures have distinct feedback. The retry button repeats the failed query without requiring more typing. Pass the signal through every asynchronous boundary and return a bounded array. The component does not implement pagination.
The showcase fetches a bundled same-origin JSON fixture over HTTP and filters it locally to simulate server search. It does not send data to a third-party service. Search for al or so, use zz for no results, and choose Fail next search before typing a new query to exercise failure and retry. Replace this fixture adapter with an actual search endpoint in production.
Asynchronous item creation
Set config.create to an async adapter that resolves a record using the configured value and label fields. This overrides options.create. The component passes { input, signal }, displays saving feedback, and lets Tom Select lock editing while the save is pending. Reject the promise to show a recoverable error and unlock the field. A successful record can have a server-generated identifier different from its label.
const labelField = { label: 'Labels', multiple: true, /** * Persist a validated label using the application adapter. * * @param {object} request - Label and cancellation context. * @param {string} request.input - Proposed label. * @param {AbortSignal} request.signal - Field lifetime. * @returns {Promise<object>} Saved record with value and text fields. */ async create({ input, signal }) { return labelService.create({ text: input, signal }); }};labelService belongs to the consumer. It must validate names and permissions, handle duplicate records, and enforce persistence requirements. Cancelling the client request does not guarantee a server write was rolled back. The showcase simulates this contract and rejects the label error. It stores no created items beyond the current page instance.
Methods, events, and lifecycle
clear()clears an enabled selection and emitsselect-changewith{ value }.- User changes update
valueand emit the same bubblingselect-changeevent. Silent parent model changes do not emit another change event. refresh()retries failed lazy initialization or recreates native chrome with the current model and learned option labels. Language and direction changes call it automatically.retryLoad()retries a failed remote search when the field is enabled.statustracks engine initialization.loadStatustracksidle,loading,ready,empty, orerror.createStatustracksidle,loading,ready, orerror.destroy()cancels pending search and creation, rejects delayed imports, removes generated controls, and releases native listeners. Alpine invokes it when the route is removed.
The native instance stays outside Alpine’s reactive proxy. Theme tokens update the control in light, dark, and custom palettes. Direction follows the document. The engine and vendor CSS are loaded from the installed package, with no runtime CDN or inline scripts. Production builds use the existing Ātrium CSP style allowance.
See the Tom Select settings and plugin catalogue for additional native options. Preserve the wrapper-owned settings above when adapting upstream examples.
Author
Laurent Declercq l.declercq@agon-innovation.ch
Version
Version: 20260923