I am working with Filament and Laravel and currently I've got these two field inputs for choosing City BASED ON Province Field, inside form()
method:
Select::make("meta.employment_state")
->label("Province")
->getSearchResultsUsing(fn (string $search): array => State::query()->where('name', 'like', "%{$search}%")->limit(10)->pluck('name', 'id')->toArray())
->getOptionLabelUsing(fn ($value): ?string => State::find($value)?->name)
->afterStateUpdated(function (Set $set) {
$set('meta.employment_city', null);
})
->live()
->searchable()
->extraAttributes(['x-data' => '{ selected: false }', 'x-on:change' => 'selected = $event.target.value !== ""'])
->dehydrated(false),
Select::make("meta.employment_city")
->label("City")
->getSearchResultsUsing(fn (string $search, Get $get): array => City::query()->whereRelation('state', 'id', '=', $get('meta.employment_state'))->where('name', 'like', "%{$search}%")->limit(10)->pluck('name', 'id')->toArray())
->getOptionLabelUsing(fn ($value): ?string => City::find($value)?->name)
->placeholder('انتخاب کنید')
->searchable()
->extraAttributes(['x-show' => 'selected', 'x-cloak' => true]),
Basically What I wanna do is that to hide the 2nd input which is city input till the 1st input is getting filled.
This must be done dynamically so I added JS attributes in order to make thing but not working and still shows the City input without the need of filling of province input and this is wrong.
So how to do this with Filament ?
You don't need to add extra attributes to hide fields. You can use Filament's visible()
or hidden()
(docs) methods, combined with $get to get the Form state. Something like this should work:
Select::make("meta.employment_state")
->label("Province")
->getSearchResultsUsing(fn (string $search): array => State::query()
->where('name', 'like', "%{$search}%")
->limit(10)
->pluck('name', 'id')
->toArray()
)
->getOptionLabelUsing(fn ($value): ?string => State::find($value)?->name)
->afterStateUpdated(function (Set $set) {
$set('meta.employment_city', null);
})
->live()
->searchable()
->dehydrated(false),
Select::make("meta.employment_city")
->label("City")
->getSearchResultsUsing(fn (string $search, Get $get): array => City::query()
->whereRelation('state', 'id', '=', $get('meta.employment_state'))
->where('name', 'like', "%{$search}%")
->limit(10)
->pluck('name', 'id')
->toArray()
)
->getOptionLabelUsing(fn ($value): ?string => City::find($value)?->name)
->placeholder('انتخاب کنید')
->searchable()
->visible(fn (Get $get) => !empty($get('meta.employment_state'))),