Skip to content

Commit

Permalink
Ensure step validation errors aren’t reset
Browse files Browse the repository at this point in the history
  • Loading branch information
aerni committed Apr 27, 2024
1 parent 2e51cf8 commit 09e4487
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/Form/Step.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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())
Expand All @@ -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;
}
Expand Down
23 changes: 23 additions & 0 deletions src/Livewire/Concerns/HandlesValidation.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@

namespace Aerni\LivewireForms\Livewire\Concerns;

use Illuminate\Support\MessageBag;

trait HandlesValidation
{
public array $allStepErrors = [];

public function bootHandlesValidation(): void
{
/**
Expand All @@ -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
Expand Down

0 comments on commit 09e4487

Please sign in to comment.