Filament: Clear Related Field Value on Parent Change

Free Snippet

Your form might have related fields set, like countries and cities. This is great, but it poses an issue—without resetting the related fields, selecting a city that doesn't belong to the country becomes possible. This can cause some errors, so let's fix it!

FilamentExamples ThumbBase (19)

How it works

When working with Dependant selects, you can reset the value of child select when the parent is changed. Just look at this scenario:

Forms\Components\Select::make('country_id')
->relationship('country', 'name')
->required(),
Forms\Components\Select::make('city_id')
->label('City')
->options(function (Forms\Get $get) {
return City::where('country_id', $get('country_id'))->pluck('name', 'id');
})
->required(),

This could lead to a user selecting a country, choosing a city, and then changing the country. The city select will still have the old value chosen. This could be a better user experience. To fix this, we can reset the city select when the country select is changed:

Forms\Components\Select::make('country_id')
->live()
->afterStateUpdated(function (Forms\Set $set) {
$set('city_id', null);
})
->relationship('country', 'name')
->required(),
Forms\Components\Select::make('city_id')
->label('City')
->live()
->options(function (Forms\Get $get) {
return City::where('country_id', $get('country_id'))->pluck('name', 'id');
})
->required(),

That's it! When the country select is changed, the city will be reset to null, preventing any confusion for the user.

A few of our Premium Examples: