F
Filament3mo ago
WEBMAS

How to hide/show a text field depending on the selected value in the select field?

Hello. I have a category table. The line contains the name and has_close_data fields. I have a table of courses. On the course creation page you can select a category and closing date. How to hide and show a field depending on the has_close_data category? Concept: Select::make('category_id') ->relationship('category', 'name') ->preload() ->searchable() >live() ->afterStateUpdated(function (?string $state) { // If the selected category_id select field value has_close_data is true, then we do not hide the close_date field; if it is false, then we hide the close_date field. }) ->required(), DatePicker::make('close_date'),
5 Replies
toeknee
toeknee3mo ago
Select::make('category_id')
->relationship('category', 'name')
->preload()
->searchable()
->live()
->required(),

DatePicker::make('close_date')
->visible(fn($record, $get) => !$record?->category?->close_date)
// OR
DatePicker::make('close_date')
->visible(fn($record, $get) => !MyCategoryModel::where('id', $get('category_id', null))->whereHas('close_date'))
Select::make('category_id')
->relationship('category', 'name')
->preload()
->searchable()
->live()
->required(),

DatePicker::make('close_date')
->visible(fn($record, $get) => !$record?->category?->close_date)
// OR
DatePicker::make('close_date')
->visible(fn($record, $get) => !MyCategoryModel::where('id', $get('category_id', null))->whereHas('close_date'))
along those lines.
WEBMAS
WEBMAS3mo ago
This does not work. If I change the value of Select::make('category_id') then the DatePicker::make('close_date') field does not change. This only works if the entry has already been created and when the page is opened. And not when category_id changes.
Povilas K
Povilas K3mo ago
@WEBMAS I've just tested it while writing a small tutorial, this worked for me
Forms\Components\Select::make('country_id')
->preload()
->relationship('country', 'name')
->live(),
Forms\Components\TextInput::make('vat_number')
->visible(
fn($record, $get) => Country::query()
->where([
'id' => $get('country_id'),
'needs_vat' => 1
])->exists()
),
Forms\Components\Select::make('country_id')
->preload()
->relationship('country', 'name')
->live(),
Forms\Components\TextInput::make('vat_number')
->visible(
fn($record, $get) => Country::query()
->where([
'id' => $get('country_id'),
'needs_vat' => 1
])->exists()
),
it's a modified second option from what @toeknee said, his first idea didn't work for me just keep in mind that my fields are different, in your case it should be Category with close_date instead of Country with needs_vat
WEBMAS
WEBMAS3mo ago
Sorry, I made a mistake in the code. Yes. Everything is working. Thank you all!