Community
Trick
Search & fill form data automatically
Aug 20, 2023
Form Builder

#Setup

We are going to start with this very simple form schema. Our goal is to automatically fill the country_region & country_subregion, based on country_name

[
TextInput::make('country_name'),
TextInput::make('country_region'),
TextInput::make('country_subregion'),
]

#Search method

Lets create a new method to handle our actual search functionality.

public static function getCountryData(?string $searchTerm = null): ?array
{
if (blank($searchTerm)) {
return null;
}
 
try {
$countryData = Http::baseUrl('https://restcountries.com/v3.1/name')
->get($searchTerm, ['fields' => 'region,subregion'])
->throw()
->json('0');
 
return $countryData;
} catch (RequestException $e) {
 
return null;
}
}

#Triggering the search

To trigger the search we are going to use a suffix action on the country_name field.

use Filament\Forms\Components\Actions\Action;
 
//...
TextInput::make('country_name')
->suffixAction(fn ($state, Set $set) =>
Action::make('search-action')
->icon('heroicon-o-magnifying-glass')
->action(function () use ($state, $set) {
$countryData = static::getCountryData($state);
 
$set('country_region', $countryData['region'] ?? null);
$set('country_subregion', $countryData['subregion'] ?? null);
})
),
ZedoX

ZedoX is full-stack web developer from Maldives. He embarked on his journey in late 2020, specializing in TALL stack (Tailwind, Alpine.js, Laravel, Livewire). Additionally, he engages in occasional contributions to open-source projects and actively participates in the Filament Community.

1
Articles
444
Stars