F
Filament15mo ago
Millio

Using "Select" form component with field cast to boolean

I have a nullable boolean field called "approved" which has 3 options true (approved) , false (rejected) and null (undecided). In my model, the approved field is cast to a boolean.
protected $casts= [
'approved' => 'boolean',
];
protected $casts= [
'approved' => 'boolean',
];
I can't seem to get this working with the filament 'edit' form though...
Forms\Components\Select::make('approved')
->options([
true => 'Approved',
false => 'Rejected'
])->nullable()
Forms\Components\Select::make('approved')
->options([
true => 'Approved',
false => 'Rejected'
])->nullable()
This correctly saves the value to database but on refreshing the edit page it always shows "Pick an option" instead of the current "Approved" / "Rejected" value from the database. If I change the options from true to 'true' and false to 'false' (with single quotation marks) it correctly DISPLAYS the current database value but now saving does not change the values in database... (I've also tried with 1/0 and '1'/ '0' but that doesn't seem to work either). Main reason I'm using Select instead of Toggle is to be able to easier differentiate between null and false. Removing the cast from the model does work but that causes other issues in other parts of the code. Thanks
1 Reply
Patrick Boivin
Patrick Boivin15mo ago
I'm not sure it's the best option but I think something like this could work:
->options([
'yes' => 'Yes',
'no' => 'No',
])
->afterStateHydrated(function ($state, $component) {
$component->state(match ($state) {
true => 'yes',
false => 'no',
default => null,
});
})
->dehydrateStateUsing(function ($state) {
return match ($state) {
'yes' => true,
'no' => false,
default => null,
};
})
->options([
'yes' => 'Yes',
'no' => 'No',
])
->afterStateHydrated(function ($state, $component) {
$component->state(match ($state) {
true => 'yes',
false => 'no',
default => null,
});
})
->dehydrateStateUsing(function ($state) {
return match ($state) {
'yes' => true,
'no' => false,
default => null,
};
})
Basically doing a manual "cast", for the context of the form field
Want results from more Discord servers?
Add your server