F
Filamentβ€’12mo ago
F alko

Custom repeater validation

Hey guys, I have a repeater with some fields and a toggle like this:
Forms\Components\Repeater::make('someRepeater')
->schema([
Forms\Components\Toggle::make('someToggle'),
]),
Forms\Components\Repeater::make('someRepeater')
->schema([
Forms\Components\Toggle::make('someToggle'),
]),
I want to validate that only 1 of the fields can be active at the same time. Any tips on how to get this done?
Solution:
I managed to use the Form\Set $set function to change the value back to false. I thought this wasn't working, but after updating van v3-alpha to v3-beta it started working πŸ™‚ I can no-longer access the ->getOldState() on the parent, but I managed to get this working with the ->getState() function and checking for $approvedCount > 1....
Jump to solution
4 Replies
Dennis Koch
Dennis Kochβ€’12mo ago
You might find something in this Discord. It was asked before.
F alko
F alkoβ€’12mo ago
So far I managed this:
Forms\Components\Toggle::make('is_approved')
->reactive()
->afterStateUpdated(function ($component, $state, EditSampleProduct $livewire) {
$livewire->resetErrorBag($component->getStatePath());

if ($state === false) {
return;
}
$items = $component->getContainer()->getParentComponent()->getOldState();
$approvedCount = collect($items)
->pluck('is_approved')
->filter()
->count();

if ($approvedCount > 0) {
$livewire->addError($component->getStatePath(), 'cannot approve more than 1.');

}
}),
Forms\Components\Toggle::make('is_approved')
->reactive()
->afterStateUpdated(function ($component, $state, EditSampleProduct $livewire) {
$livewire->resetErrorBag($component->getStatePath());

if ($state === false) {
return;
}
$items = $component->getContainer()->getParentComponent()->getOldState();
$approvedCount = collect($items)
->pluck('is_approved')
->filter()
->count();

if ($approvedCount > 0) {
$livewire->addError($component->getStatePath(), 'cannot approve more than 1.');

}
}),
Yes I can still save my form now.
Solution
F alko
F alkoβ€’12mo ago
I managed to use the Form\Set $set function to change the value back to false. I thought this wasn't working, but after updating van v3-alpha to v3-beta it started working πŸ™‚ I can no-longer access the ->getOldState() on the parent, but I managed to get this working with the ->getState() function and checking for $approvedCount > 1.
Daniel
Danielβ€’9mo ago
any ideas how i can prevent form submission when using the above form to add erros on duplicate repeater items? the error gets displayed under the field but the form can be still submitted