Skip to content

Locale switching blocked by form validation (getState triggers validate) #43

@micheldraad

Description

@micheldraad

Bug

Switching locales via LocaleSwitcher is impossible when a required field is empty, because updatedActiveLocale() in HasActiveLocaleSwitcher calls $this->form->getState() which triggers validate().

https://github.com/lara-zeus/spatie-translatable/blob/main/src/Resources/Concerns/HasActiveLocaleSwitcher.php#L53

Steps to reproduce

  1. Create a translatable resource with a required field (e.g. TextInput::make('name')->required())
  2. Open the edit page
  3. Switch to another locale where the required field is empty
  4. Result: ValidationException is thrown, locale resets back

Expected behavior

Locale switching should always work. Validation should only happen on save.

Suggested fix

Replace $this->form->getState() with $this->form->getRawState() in updatedActiveLocale():

- $this->otherLocaleData[$this->oldActiveLocale] = Arr::only(
-     $this->form->getState(),
-     $translatableAttributes
- );
-
- $this->form->fill([
-     ...Arr::except(
-         $this->form->getState(),
-         $translatableAttributes
-     ),
-     ...$this->otherLocaleData[$this->activeLocale] ?? [],
- ]);
+ $this->otherLocaleData[$this->oldActiveLocale] = Arr::only(
+     $this->form->getRawState(),
+     $translatableAttributes
+ );
+
+ $this->form->fill([
+     ...Arr::except(
+         $this->form->getRawState(),
+         $translatableAttributes
+     ),
+     ...$this->otherLocaleData[$this->activeLocale] ?? [],
+ ]);

getRawState() returns form state without triggering validation, which is appropriate here since we're just swapping locale data, not saving.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions