v0.0.2
Demos (demo panel, opens in a new tab)

Combobox

A select box you search by typing, for long lists; it offers single or multiple selection, search on the server and adding new values.

zb:combobox zubazar/ui-pro

PRO

Needs the Zubazar UI Pro JavaScript: the import line in the Configuration and build guide or @zubazarUiScripts loads it.

This component is in Zubazar UI Pro; Zubazar UI Pro brings Zubazar UI with it. Installing Zubazar UI Pro →

Single selection

Single selection: view
BLADE

Pass the options in options and the selected value in value.

blade
<zb:combobox name="branch_id" label="Branch" value="2" :options="[
    1 => 'Kadıköy Branch', 2 => 'Beşiktaş Branch', 3 => 'Üsküdar Branch',
    4 => 'Çankaya Branch', 5 => 'Karşıyaka Branch', 6 => 'Nilüfer Branch', 7 => 'Ataşehir Branch',
    8 => 'Şişli Branch', 9 => 'Çamlıca Branch', 10 => 'Iğdır Branch',
]" />
PropValues
optionsvalue => label, or option arrays
valueSelected value (compared as a string)

Multiple selection

Multiple selection: view
BLADE

With multiple, selections become removable chips; max-chips limits how many chips show.

blade
<zb:combobox name="branches" label="Branches" multiple clearable :max-chips="3" :value="[1, 3, 4, 8, 9]" :options="[
    1 => 'Kadıköy Branch', 2 => 'Beşiktaş Branch', 3 => 'Üsküdar Branch',
    4 => 'Çankaya Branch', 5 => 'Karşıyaka Branch', 6 => 'Nilüfer Branch', 7 => 'Ataşehir Branch',
    8 => 'Şişli Branch', 9 => 'Çamlıca Branch', 10 => 'Iğdır Branch',
]" />
PropValues
multipleMultiple selection; the value is an array
max-chipsNumber of visible chips
clearable× that clears everything

Rich options and groups

Rich options and groups: view
BLADE

Pass an option as an array to add description, avatar, icon, disabled and group.

blade
<zb:combobox name="assignee" label="Assignee" placeholder="Select a staff member" :options="[
    ['value' => 1, 'label' => 'Ayşe Yılmaz', 'description' => 'ayse.yilmaz@example.com', 'icon' => 'shield-check', 'group' => 'Managers'],
    ['value' => 2, 'label' => 'Mehmet Kaya', 'description' => 'mehmet.kaya@example.com', 'icon' => 'shield-check', 'group' => 'Managers'],
    ['value' => 3, 'label' => 'Zeynep Arslan', 'description' => 'On leave', 'icon' => 'briefcase', 'group' => 'Sales team', 'disabled' => true],
    ['value' => 4, 'label' => 'Emre Demir', 'description' => 'emre.demir@example.com', 'icon' => 'briefcase', 'group' => 'Sales team'],
    ['value' => 5, 'label' => 'Şule Öztürk', 'description' => 'sule.ozturk@example.com', 'icon' => 'briefcase', 'group' => 'Sales team'],
    ['value' => 6, 'label' => 'Gökhan Çelik', 'description' => 'Accounting', 'icon' => 'calculator', 'group' => 'Head office'],
    ['value' => 7, 'label' => 'İsmail Işık', 'description' => 'Technical support', 'icon' => 'wrench-screwdriver', 'group' => 'Head office'],
]" />
PropValues
descriptionSecond line, searched
avatarImage URL
iconHeroicons name
disabledCannot be selected
groupGathers options under a heading

Search through a Livewire method

Search through a Livewire method: view
BLADE

Give search a method on the Livewire component that holds the box; as the user types, the method is called and the options it returns are listed.

blade
<zb:combobox
    wire:model="assigneeId"
    label="Assignee"
    search="searchStaff"
    :selected-options="Staff::whereKey($assigneeId)->pluck('name', 'id')"
    placeholder="Search staff"
    clearable
/>
PropValues
searchName of the Livewire method
selected-optionsLabels of the selected values
debounce300 (ms)
min-chars0

Clearing and limits

Clearing and limits: view
BLADE

clearable adds a × that clears the selection, and max sets the most values in multiple selection.

blade
<div class="grid gap-4 sm:grid-cols-2">
    <zb:combobox name="priority" label="Priority" value="2" clearable :searchable="false" :options="[1 => 'Low', 2 => 'Normal', 3 => 'High', 4 => 'Urgent']" />
    <zb:combobox name="categories" label="Categories (up to 3)" multiple :max="3" :value="['electronics', 'books']" :options="[
        'electronics' => 'Electronics', 'clothing' => 'Clothing', 'books' => 'Books', 'home' => 'Home & living', 'sports' => 'Sports',
    ]" />
</div>
PropValues
clearableClears with ×
maxMaximum selections (multiple)
searchabletrue | false
close-on-selectsingle: true · multiple: false

Props

The values the component takes. What are props and slots?

PropTypeDefaultDescription
label—nullLabel above the box
options—[]value => label; option arrays; nested array (group); enum; records with id/name fields
value—nullInitial value (multiple: array); when wire:model / x-model is present, it takes precedence
multiplebooleanfalseMultiple selection; selections are removable chips
placeholder—Select…Text shown when nothing is selected
search-placeholder—Search…Hint in the empty box while the list is open
empty—No resultsText shown when nothing matches
hint—nullHelp text below, shown when there is no error
input-class—nullClasses of the text input itself; class places the whole field
clearablebooleanfalse× that clears the selection (Backspace too in single selection)
creatablebooleanfalseAdds text that is not in the list; combobox-created event
searchablebooleantruefalse: typing off; short lists then don't open the phone keyboard
max—nullmultiple: maximum selections; a warning is shown at the limit
max-chips—nullmultiple: number of visible chips, the rest as "+N"
close-on-select—single: true · multiple: falseWhether the list closes after a selection
search—nullLivewire method: fn (string $query): array (option list)
url—nullJSON URL; called with ?q=
debouncenumber300Wait for remote search (ms)
min-charsnumber0Minimum characters before a remote search
selected-options—[]Labels of the selected values in remote lists
limitnumber200Maximum options drawn at once in a local list
disabledbooleanfalseLocks; the hidden field is not submitted
requiredbooleanfalse* on the label; browser validation and aria-required
name—nullClassic form field (multiple: name[]); error key
wire:model / x-model— — single: value · multiple: array; .live and .live.blur work
Option keys— — value, label, description, avatar, icon, disabled, group
Event: combobox-created— — detail: { name, value }; in Livewire, #[On('combobox-created')]
Event: change— — From the root element when the user changes the selection (bubbles)

Slots: id goes to the box itself (the label's for value), and aria-label (when there is no visible label) goes to the box and the list. The outer wrapper holds the value, so wire:model, x-model, events and class, style, x-show, wire:key stay there. autofocus, tabindex, autocomplete, inputmode, spellcheck, enterkeyhint, autocapitalize, aria-* and data-* go to the text field; your value replaces the kit's default (data-dirty-ignore stays on the outer wrapper). Keyboard: ↓/↑ navigate (skipping disabled options), Home/End, PageUp/PageDown, Enter selects, Escape closes, Tab closes and moves on, Backspace removes the last selection. Screen readers announce the selected value, every selection and removal, and the number of results.

Advanced

10 examples

The search method

PHP

The method takes the typed text (string $query, possibly empty) and returns option arrays, a value => label array or ComboboxOptions::from(…), which turns icon names into drawable paths. #[Json] (or #[Renderless]) runs the method without re-rendering the component.

php
use Zubazar\Panel\ComboboxOptions;
use Livewire\Attributes\Json;
use Livewire\Component;

class TicketForm extends Component
{
    public ?int $assigneeId = null;

    // <zb:combobox search="searchStaff" />: receives the typed text, returns the options.
    #[Json]
    public function searchStaff(string $query): array
    {
        $staff = Staff::query()
            ->when($query !== '', fn ($builder) => $builder->where(fn ($builder) => $builder
                ->where('name', 'like', '%'.$query.'%')
                ->orWhere('email', 'like', $query.'%')))
            ->orderBy('name')
            ->limit(20)
            ->get();

        return ComboboxOptions::from($staff->map(fn (Staff $person) => [
            'value' => $person->id,
            'label' => $person->name,
            'description' => $person->email,
            'group' => $person->department,
        ]));
    }
}

Search through a JSON URL

Search through a JSON URL: view
BLADE

On pages without Livewire, give url a JSON URL; the typed text is added as ?q=. The response can be an option list, { "data": [...] } (API resources, paginators) or a value => label object.

blade
<zb:combobox name="province_id" label="Province" url="/api/provinces" :min-chars="2" placeholder="Search provinces" clearable />
PropValues
urlJSON URL (?q= is appended)
min-charsMinimum characters before searching

Endpoint

PHP

The URL receives the typed text in the q parameter and returns the options. The session cookie is sent (same-origin), so routes behind the auth middleware work too.

php
use Illuminate\Http\Request;

Route::get('/api/provinces', function (Request $request) {
    return Province::query()
        ->where('name', 'like', '%'.$request->query('q').'%')
        ->orderBy('name')
        ->limit(20)
        ->get()
        ->map(fn (Province $province) => ['value' => $province->id, 'label' => $province->name]);
})->middleware('auth');

Adding new values

Adding new values: view
BLADE

With creatable, text with no match in the list gets an "Add “…”" row at the end; a difference in letter case or Turkish letters doesn't count as new (typing "WHOLESALE" finds "Wholesale" instead of adding it). Enter or a click selects the text as the value and dispatches the combobox-created event from the root element; its detail holds name and value.

blade
<zb:combobox name="tags" label="Tags" multiple creatable :value="['urgent']" :options="[
    'urgent' => 'Urgent', 'priority' => 'Priority', 'wholesale' => 'Wholesale', 'business' => 'Business customer',
]" />
PropValues
creatableAdds text that is not in the list
combobox-createdEvent; detail: { name, value }

Saving an added value

PHP

The Livewire component listens for the event with #[On]; the parameters are the fields of the event's detail. If, after saving, you set the property to the new record's ID and update the option list, the combobox picks up both on the next render.

php
use Livewire\Attributes\On;

#[On('combobox-created')]
public function tagAdded(string $name, string $value): void
{
    if ($name === 'tags') {
        Tag::firstOrCreate(['name' => $value]);
    }
}

Classic form

Classic form: view
BLADE

When name is set without wire:model, the value is sent in hidden fields: name in single selection and name[] for each value in multiple selection. With required, the form isn't sent without a selection.

blade
<form action="/orders" method="POST" class="space-y-4">
    @csrf
    <zb:combobox name="branch_id" label="Branch" required :options="[1 => 'Kadıköy Branch', 2 => 'Beşiktaş Branch', 3 => 'Çankaya Branch']" />
    <zb:combobox name="tags" label="Tags" multiple :options="['urgent' => 'Urgent', 'priority' => 'Priority', 'wholesale' => 'Wholesale']" />
    <zb:button type="submit">Save</zb:button>
</form>
PropValues
nameHidden field name (multiple: name[])
requiredSelection is required

Validation error and disabled

Validation error and disabled: view
BLADE

If the field has a validation error, the box gets a red border and the message shows below it; without an error, hint shows. disabled locks the box; in a classic form its value isn't sent.

blade
<div class="grid gap-4 sm:grid-cols-2">
    <zb:combobox name="branch" label="Branch" required :options="[1 => 'Kadıköy Branch', 2 => 'Beşiktaş Branch']" />
    <zb:combobox name="locked_branch" label="Branch (locked)" value="2" disabled hint="Cannot be changed once the order is being prepared." :options="[1 => 'Kadıköy Branch', 2 => 'Beşiktaş Branch']" />
</div>
PropValues
hintShown when there is no error
disabledLocks; the value is not submitted

Inside a modal, drawer or table

Inside a modal, drawer or table: view
BLADE

The list opens without being clipped inside a modal, a drawer or a horizontally scrolling table. While the list is open, Escape closes only the list and the modal stays open.

blade
<div class="flex flex-wrap gap-2">
    <zb:modal.trigger name="assign-ticket"><zb:button>Assign ticket</zb:button></zb:modal.trigger>
    <zb:drawer.trigger name="ticket-filters"><zb:button variant="white">Filters</zb:button></zb:drawer.trigger>
</div>

<zb:modal name="assign-ticket" title="Assign ticket">
    <div class="space-y-4">
        <zb:combobox name="agent" label="Agent" :options="[1 => 'Ayşe Yılmaz', 2 => 'Mehmet Kaya', 3 => 'Zeynep Arslan', 4 => 'Emre Demir', 5 => 'Şule Öztürk', 6 => 'Gökhan Çelik', 7 => 'İsmail Işık', 8 => 'Ömer Güneş']" />
        <zb:combobox name="ticket_tags" label="Tags" multiple :options="['billing' => 'Billing', 'return' => 'Return', 'shipping' => 'Shipping', 'technical' => 'Technical issue']" />
    </div>
    <zb:slot:footer>
        <zb:button variant="white" x-on:click="ZubazarUI.modal.close('assign-ticket')">Cancel</zb:button>
        <zb:button>Assign</zb:button>
    </zb:slot:footer>
</zb:modal>

<zb:drawer name="ticket-filters" title="Filters">
    <zb:combobox name="statuses" label="Status" multiple :options="['pending' => 'Pending', 'reviewing' => 'Under review', 'approved' => 'Approved', 'rejected' => 'Rejected']" />
</zb:drawer>

<div class="overflow-x-auto rounded-sm ring-1 ring-line">
    <table class="w-full min-w-[34rem] text-left text-sm">
        <thead class="bg-sunken text-xs text-muted">
            <tr><th class="px-3 py-2 font-medium">Ticket</th><th class="px-3 py-2 font-medium">Status</th><th class="px-3 py-2 font-medium">Agent</th></tr>
        </thead>
        <tbody class="text-body">
            <tr>
                <td class="px-3 py-2">#1042 · Return request</td>
                <td class="px-3 py-2">Pending</td>
                <td class="w-56 px-3 py-2"><zb:combobox name="agent_1042" aria-label="Agent" :options="[1 => 'Ayşe Yılmaz', 2 => 'Mehmet Kaya', 3 => 'Zeynep Arslan', 4 => 'Emre Demir', 5 => 'Şule Öztürk', 6 => 'Gökhan Çelik', 7 => 'İsmail Işık', 8 => 'Ömer Güneş']" /></td>
            </tr>
        </tbody>
    </table>
</div>
PropValues
zb:modal · zb:drawerOpens without clipping
overflow-x-autoThe table wrapper does not clip it

With Alpine

With Alpine: view
BLADE

x-model binds to a value in single selection and to an array in multiple selection. When the user changes the selection, the root element dispatches a bubbling change event.

blade
<div x-data="{ branch: '3', regions: [] }" class="space-y-3">
    <zb:combobox x-model="branch" label="Branch" :options="[1 => 'Kadıköy Branch', 2 => 'Beşiktaş Branch', 3 => 'Üsküdar Branch']" />
    <zb:combobox x-model="regions" label="Regions" multiple :options="[1 => 'Marmara', 2 => 'Aegean', 3 => 'Central Anatolia']" />
    <p class="text-sm text-dim">branch: <span x-text="JSON.stringify(branch)"></span> · regions: <span x-text="JSON.stringify(regions)"></span></p>
</div>
PropValues
x-modelsingle: value · multiple: array
changeWhen the user makes a selection (bubbles)

With Livewire

BLADE

wire:model, .live and .live.blur work; .blur alone sends no request in Livewire 4. options, disabled and the validation error update with the new render; this is how a district list changes when a city is picked.

blade
<zb:combobox wire:model.live="provinceId" label="Province" :options="$provinces->pluck('name', 'id')" />
<zb:combobox wire:model.live.blur="districtId" label="District" :options="$districts->pluck('name', 'id')" :disabled="! $provinceId" />
<zb:combobox wire:model="staff" label="Staff" multiple :options="$staff->pluck('name', 'id')" />
PropValues
wire:model.live · .live.blur · .live.debounce.500ms
wire:keySet it when rendering in a loop

Developer notes

Events, hooks and details
  • Alpine isn't needed; the box's own JavaScript chunk downloads the first time one is on the page, with nothing to register.
  • registerCombobox(Alpine) does nothing now; it stays until 3.0.
  • Search ignores letter case and Turkish letters: typing "sisli" finds "Şişli Branch", "igdir" finds "Iğdır Branch", and the matching part is highlighted.
  • In the list, Enter selects and doesn't submit the form.
  • In multiple selection the list stays open after a selection; clicking a selected option again removes it. When the chips don't fit, the box grows line by line; chips beyond max-chips are counted as "+2" and their names show on hover.
  • options turns nested arrays (['Managers' => [1 => 'Ayşe', …]]) into groups and also reads enum lists (Status::cases(), with the text from label() if there is one), arrays with id and name fields and models.
  • Options with the same group gather under a heading that sticks to the top while the list scrolls; disabled options are visible, but the keyboard skips them.
  • In a remote search, the request goes debounce ms (300 by default) after typing stops, and a spinner turns in the box while it waits. Unless min-chars is set, the list is also asked with an empty text each time it opens.
  • selected-options gives the selected value's name when the page first opens; the selected names stay even when the results change.
  • Picking an option sends no new search; wire:model.live sends the change in its own request.
  • If order matters in the search method, return a list: an array with numeric keys (pluck()) becomes an object in JSON and the browser sorts its keys.
  • With url, other parameters in the URL are kept and { id, name } records are read too; a late, older response never overwrites newer results.
  • At the max limit a warning appears and the other options are disabled; the selected ones can still be removed.
  • In multiple selection, tags.* errors show too; for names with brackets, the error of address.city is used for address[city] and regions.inner for regions[inner][].
  • The list is drawn above the page with fixed positioning: it opens below the box, or above it when there is no room, and follows the box as the page scrolls. On phones it opens at the box's width, and rows are at least 40 px tall.
  • Values are compared as strings: the number 3 from Livewire or Alpine selects the option with the '3' key.
  • x-model binds to the root element's value property (there is no Alpine scope or x-modelable).
  • The inner part of the box is protected with wire:ignore: a re-render doesn't break the open list, the typed text or the selection.
  • The previews of examples that need a server run on a fake answer in the browser; the code shown is the real usage.

Events

EventdetailDescription
combobox-created{ name, value }Sent from the root when creatable adds text that is not in the list; it bubbles.
Zubazar UI · ZubazarDesigned for people.