F
Filament10mo ago
AxlF

Is it possible to load select options asynchronous?

Hey, I would like to create some sort of location finder. For that I want to utilize a places api, where I would want a search based on min 3 characters and return the search results. When the user selects a result I want to set other form fields, like postcode or city. Is that possible? I haven't found a Select example with async data... Thanks
2 Replies
wagnerfnds
wagnerfnds10mo ago
Yes it is possible, search in the docs about the $set function to change values of fields and maybe the afterupdate callback to make the changes when a option is selected
AxlF
AxlFOP10mo ago
Thank you. I got a working solution with a Select Field. It something like this:
Select::make('location')
->live(onBlur: true)
->searchable()
->required()
->getSearchResultsUsing(function (string $search, Get $get): array {
if (strlen($search) < 3) {
return [];
}
$result = $this->postcode($search, 'de'); // API call

return collect($result)
->mapWithKeys(fn ($item) => [
$item['postal'] => $item['label'],
])
->toArray();
})
->afterStateUpdated(function (?string $state, Set $set) {
$result = $this->postcode($state, 'de');
$result = collect($result)->unique('postal')->last();

if ($result) {
$set('postal', $result['postal']); // Set hidden fields
$set('city', $result['city']); // Set hidden fields
}
}),
Select::make('location')
->live(onBlur: true)
->searchable()
->required()
->getSearchResultsUsing(function (string $search, Get $get): array {
if (strlen($search) < 3) {
return [];
}
$result = $this->postcode($search, 'de'); // API call

return collect($result)
->mapWithKeys(fn ($item) => [
$item['postal'] => $item['label'],
])
->toArray();
})
->afterStateUpdated(function (?string $state, Set $set) {
$result = $this->postcode($state, 'de');
$result = collect($result)->unique('postal')->last();

if ($result) {
$set('postal', $result['postal']); // Set hidden fields
$set('city', $result['city']); // Set hidden fields
}
}),
But, I want a solution without a Select Field. The problem is, that if I click in that select, another Input Field with the search prompt appears. I need suggestions in a box below the input field, where the user is typing. I tried to create a custom field and I got the async search working with alpine. It's all fine, but I don't know, how to get the data to the form. The user types, a suggestion box appears and if the user selects a row, I have the needed data as an array. e.g.: The user types "910" and clicks on "91058 Erlangen, Germany". How would I get the underlying array of the selected label to my main form?
Want results from more Discord servers?
Add your server