F
Filament11mo ago
Barney

Select field default value

Hi, Im having trouble with data editing. When I click 'Edit' on a row, the 'region' select field should show the default value, but it keeps showing 'Select an option' instead. What am I doing wrong?
Forms\Components\Select::make('region')
->options(Region::all()->pluck('name', 'id')->toArray())
->default(function (?Model $record) {
if ($record){
return $record->area->region->id;
}
})
->live(),
Forms\Components\Select::make('area_id')
->relationship('area', 'name')
->options(function (Get $get, ?Model $record) {
if($get('region')){
return Area::where('region_id',$get('region'))->get()->pluck('name', 'id');
}
if ($record){
return Area::where('region_id',$record->area->region->id)->get()->pluck('name', 'id');
}
})
->live(),
Forms\Components\Select::make('region')
->options(Region::all()->pluck('name', 'id')->toArray())
->default(function (?Model $record) {
if ($record){
return $record->area->region->id;
}
})
->live(),
Forms\Components\Select::make('area_id')
->relationship('area', 'name')
->options(function (Get $get, ?Model $record) {
if($get('region')){
return Area::where('region_id',$get('region'))->get()->pluck('name', 'id');
}
if ($record){
return Area::where('region_id',$record->area->region->id)->get()->pluck('name', 'id');
}
})
->live(),
Solution:
Thank you! it solved my issue, for anyone asking about this, I added the mutateFormDataBeforeFill function on the Edit page ```php protected function mutateFormDataBeforeFill(array $data): array { $data['region'] = Area::find($data['area_id'])->region->id; ...
Jump to solution
3 Replies
awcodes
awcodes11mo ago
Default only works on create pages. It doesn’t make sense in the context of an edit page as the value should have been set by then.
Dennis Koch
Dennis Koch11mo ago
You can use lifecycle hooks like mutateFormDataBeforeFill(or similar naming) to set default values.
Solution
Barney
Barney11mo ago
Thank you! it solved my issue, for anyone asking about this, I added the mutateFormDataBeforeFill function on the Edit page
protected function mutateFormDataBeforeFill(array $data): array
{
$data['region'] = Area::find($data['area_id'])->region->id;

return $data;
}
protected function mutateFormDataBeforeFill(array $data): array
{
$data['region'] = Area::find($data['area_id'])->region->id;

return $data;
}