From 09e4487a95f5b5137dfdb178aa7a03cc24a9b1bd Mon Sep 17 00:00:00 2001 From: Michael Aerni Date: Sat, 27 Apr 2024 17:51:08 -0400 Subject: [PATCH] =?UTF-8?q?Ensure=20step=20validation=20errors=20aren?= =?UTF-8?q?=E2=80=99t=20reset?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Form/Step.php | 13 ++++++------ src/Livewire/Concerns/HandlesValidation.php | 23 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/Form/Step.php b/src/Form/Step.php index 6b8ac8a9..7c638d2c 100644 --- a/src/Form/Step.php +++ b/src/Form/Step.php @@ -2,11 +2,12 @@ namespace Aerni\LivewireForms\Form; -use Aerni\LivewireForms\Enums\StepStatus; -use Aerni\LivewireForms\Fields\Field; -use Illuminate\Support\Collection; -use Illuminate\Support\Str; use Livewire\Livewire; +use Illuminate\Support\Str; +use Illuminate\Support\Collection; +use Aerni\LivewireForms\Fields\Field; +use Aerni\LivewireForms\Enums\StepStatus; +use Illuminate\Support\MessageBag; class Step { @@ -88,7 +89,7 @@ public function validate(): bool return false; } - $errorBag = Livewire::current()->getErrorBag(); + Livewire::current()->storeAllStepErrors(); $rules = $this->fields() ->mapWithKeys(fn (Field $field) => $field->rules()) @@ -101,7 +102,7 @@ public function validate(): bool * This leads to error messages of other steps being reset as well. * To prevent this, we restore the previous error bag after the validation. */ - Livewire::current()->setErrorBag($errorBag); + Livewire::current()->restoreAllStepErrors(); return true; } diff --git a/src/Livewire/Concerns/HandlesValidation.php b/src/Livewire/Concerns/HandlesValidation.php index c0a566b5..c75c1e0d 100644 --- a/src/Livewire/Concerns/HandlesValidation.php +++ b/src/Livewire/Concerns/HandlesValidation.php @@ -2,8 +2,12 @@ namespace Aerni\LivewireForms\Livewire\Concerns; +use Illuminate\Support\MessageBag; + trait HandlesValidation { + public array $allStepErrors = []; + public function bootHandlesValidation(): void { /** @@ -18,6 +22,25 @@ public function bootHandlesValidation(): void }); } + public function storeAllStepErrors(): void + { + $currentErrors = $this->getErrorBag()->messages(); + + $stepFields = $this->currentStep()->fields()->map->key()->flip(); + + $resolvedErrors = collect($stepFields)->diffKeys($currentErrors); + + $this->allStepErrors = collect($this->allStepErrors) + ->merge($currentErrors) + ->diffKeys($resolvedErrors) + ->toArray(); + } + + public function restoreAllStepErrors(): void + { + $this->setErrorBag(new MessageBag($this->allStepErrors)); + } + protected function rules(): array { return $this->fields