Unable to set a default value for \Filament\Forms\Components\Select
I want to select predefined options in my Select component. Looking at the docs, if a Select component has
options()
set, and a default()
state set - it should automatically preselect an option. Unfortunately, the example in the docs does not do anything - the default('draft')
method call doesn't do anything in this piece of code:
I've tried setting default values via the state()
method, and a bunch of others. The only working method that actually did anything was the relationship()
one. But it queries eloquent for options and selected values. However, mine are static.
Am I missing something obvious or doesn't this basic Select component support preselected values? Even basic HTML can do that π€
I was stuck with this in v2 and was hoping for a solution in v3, but nothing has changed. So my question is valid for both.7 Replies
are you using admin panel? Is it a custom page?
I'm using admin panel and it's just a regular page - nothing custom. I haven't even seen any examples online, showing how to preselect options. So it's weird.
I have a resource, it has a defined form. In the form, I call
Select::make('test')->multiple()->options(['foo' => 'FOO', 'bar' => 'BAR'])
So how do I make it preselect foo
or bar
? Assuming these options are not from a relationship->default(['foo', 'bar'])
this will work in the Create Page/ActionI'll try it on the Create page. I've been using it on the Edit page at the moment and it doesn't work π€
Wow that's so weird, it's indeed working with the Create page. Thanks for the help @leandro_ferreira ! Any idea why it wouldn't work in the Edit page?
Because in edit the record has already been saved and that default value would have been saved to the record from the create page.
Edit page should get the database values.. if you want to override it you can use
afterStateHydrated
or formatStateUsing
..That makes sense, thank you for your time.
Just for context, I'm using the event sourcing architecture so the default CRUD operations don't cut it here, so I was looking to format the state in my own way, instead of overriding the update process in multiple places.
I'll try to format the state as you've suggested or override a couple of methods in a worst-case scenario
In case anybody encounters a similar situation - I solved this with the
formatStateUsing
method. Thanks for much for the help again