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'),]
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; }}
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 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.