Tricks

Workaround to display Spatie Translation on Modals

Sep 9, 2022
Mahfoud Galfout
Admin panel, Form builder

This trick is for people who use Spatie Translatable official plugin and have to deal with Modals. As you may know, currently, Filament doesn't support this case due to Livewire limitation, that maybe possible starting from v3.

Awaiting for a core solution, here is a little and clean trick to display the correct translation on both View and Edit Modals, using the method afterStateHydrated() of the Field lifecycle Hydration advanced features.

return $form
->schema([
TextInput::make('name')
->afterStateHydrated(function (TextInput $component, $state) {
if ($state !== null) {
(isset($state[app()->getLocale()]))
? $component->state($state[app()->getLocale()])
: $component->state($state[config('app.fallback_locale')]);
}
}),
TextInput::make('description'),
]);

Here is a screenshot of the result of the above code. You can notice the difference in display between the name and description fields (which were intentionally omitted on description field for didactical purpose).

Note that this will handle correctly the Modal only Resources, so don't forget to remove the Create, Edit and View pages, else, further checks will be required.

  • ~~'create' => Pages\CategoryNames::route('/create'),~~
  • ~~'view' => Pages\CategoryNames::route('/{record}'),~~
  • ~~'edit' => Pages\CategoryNames::route('/{record}/edit'),~~
public static function getPages(): array
{
return [
'index' => Pages\CategoryNames::route('/'),
];
}

No comments yet…