F
Filament2y ago
Sven

Default Key-Value when creating a new record

While we can set a default value for a normal input field, I can't seem to find the option to do the same for a key-value field. Is it possible to set a default array value on page load?
Solution:
this should be ```php ->default([ 'sizes' => 'S, M, L, XL, XXL' ])...
Jump to solution
5 Replies
awcodes
awcodes2y ago
What have you tried? Please share the code.
Sven
SvenOP2y ago
The first thing I have tried was hook into the afterStateUpdated method of a TextInput field and set the value of the KeyValue with an empty array:
Forms\Components\TextInput::make('name')
->label('Naam')
->required()
->live(onBlur: true)
->afterStateUpdated(function (string $operation, $state, Forms\Set $set) {
if ($operation !== 'create') {
return;
}
$set('meta', ['sizes' => [],'colors' => [], 'types' => []]);
}),
Forms\Components\TextInput::make('name')
->label('Naam')
->required()
->live(onBlur: true)
->afterStateUpdated(function (string $operation, $state, Forms\Set $set) {
if ($operation !== 'create') {
return;
}
$set('meta', ['sizes' => [],'colors' => [], 'types' => []]);
}),
The second thing I have tried was use the default method on the KeyValue field:
Forms\Components\KeyValue::make('meta')
->label('Eigenschappen')
->keyLabel('Variatie')
->columnSpan('full')
->keyPlaceholder('Property name')
->reorderable()
->default([
'sizes' => ['S', 'M', 'L', 'XL', 'XXL'],
'colors' => [],
'types' => ['VERPAKT','GEVOUWEN','STICKERS'],
]),
Forms\Components\KeyValue::make('meta')
->label('Eigenschappen')
->keyLabel('Variatie')
->columnSpan('full')
->keyPlaceholder('Property name')
->reorderable()
->default([
'sizes' => ['S', 'M', 'L', 'XL', 'XXL'],
'colors' => [],
'types' => ['VERPAKT','GEVOUWEN','STICKERS'],
]),
` While the the above default values get shown inside of the KeyValue field, I am getting the following error when submitting the resource form: Filament\Forms\Components\KeyValue::Filament\Forms\Components{closure}(): Argument #1 ($value) must be of type ?string, array given However, when I manually add the above values, the form submits succesfully and the values get saved as an array inside of my database.
awcodes
awcodes2y ago
KeyValue isn’t designed to work with arrays like this.
Solution
LeandroFerreira
this should be
->default([
'sizes' => 'S, M, L, XL, XXL'
])
->default([
'sizes' => 'S, M, L, XL, XXL'
])
Sven
SvenOP2y ago
Yea that works, cheers.

Did you find this page helpful?