F
Filamentβ€’10mo ago
gladjanus43

Checkbox List, select at least one

Hi, I have a checkbox list where at least one checkbox needs to be selected. I thought it would be easy using the required but it is allowing me to save the form without one checkbox selected The checkboxlist is in a custom livewire component
Forms\Components\CheckboxList::make('users')
->bulkToggleable()
->options(User::all()->pluck('name', 'name'))
->hidden(fn() =>...)
->required()
Forms\Components\CheckboxList::make('users')
->bulkToggleable()
->options(User::all()->pluck('name', 'name'))
->hidden(fn() =>...)
->required()
I also tried adding
->rules([function()....])
->rules([function()....])
But I cant get this working either. It never even validates the thing
6 Replies
Patrick
Patrickβ€’10mo ago
thats because a non checked is also a valid state for it to be required can you add a validation rule min:1 see if that works?
gladjanus43
gladjanus43OPβ€’10mo ago
unfortunatly the min method is not present on checkboxlist. Tried the ->rules(['min:1']) but it skips it as well... I have the feeling that it skips the entire rules() method. If i do this:
Forms\Components\CheckboxList::make('users')
->required()
->bulkToggleable()
->rules([
function () {
return function (string $attribute, $value, Closure $fail) {
dd('test if executed');
if ($value === 'foo') {
$fail('The :attribute is invalid.');
}
};
},
])
->options(User::all()->pluck('name', 'name'))
Forms\Components\CheckboxList::make('users')
->required()
->bulkToggleable()
->rules([
function () {
return function (string $attribute, $value, Closure $fail) {
dd('test if executed');
if ($value === 'foo') {
$fail('The :attribute is invalid.');
}
};
},
])
->options(User::all()->pluck('name', 'name'))
It skips the check... Which is weird right? It should just dump the string when pressed save Anybody has some insight into these validation rules? I cant get them working 😦
Patrick
Patrickβ€’10mo ago
mm can you solve it with a multi select instead of a checkbox list ? πŸ˜›
Tim van Heugten
Tim van Heugtenβ€’10mo ago
Just validate the array and check for at least one true value. This will get you going: https://stackoverflow.com/questions/45758449/laravel-validate-at-least-one-item-in-a-form-array
Stack Overflow
Laravel validate at least one item in a form array
I have a form with a series of numbers in an array: <input type="number" name="items[{{ $sku }}]" min="0" /> <input type="number" name="items[{{ $sku }}]" min="0" /> <input type="nu...
gladjanus43
gladjanus43OPβ€’9mo ago
Allright thanks, but for this to work I need to be able to execute a rule in the ->rules() method. Somehow I cant even get the function inside rules to work...
Tim van Heugten
Tim van Heugtenβ€’9mo ago
Show your code, did you create a separate file or are you using a closure? Did you wrap it in an array? This is what the docs describe: https://filamentphp.com/docs/3.x/forms/validation#custom-rules
Want results from more Discord servers?
Add your server