How to fix the Filament resource list locale switcher
TL;DR: add this method to your list records class:
class ListFoo extends ListRecords
{
// ...
public function getActiveSchemaLocale(): ?string
{
return $this->getActiveFormsLocale();
}
}
Background
Filament V4 was released a couple of weeks ago and with it came the news that the official Spatie Translatable plugin is now deprecated.
Lara Zeus have forked the plugin at lara-zeus/spatie-translatable
and are now maintaining it, along with fixing some issues. There is currently still one issue that’s present which is the resource list view’s locale switcher doesn’t work.
When viewing the resource list, switching the locale has no effect.
This was reported in Translatable columns ignore LocaleSwitcher in ListResource (#14).
As a workaround, you can add the getActiveSchemaLocale
method above into your resource list class which will make the switcher work again.
Why does it work?
If we look into Filament\Schemas\Concerns\InteractsWithSchemas
, you’ll see there is already a getActiveSchemaLocale
method but it returns null
.
public function getActiveSchemaLocale(): ?string
{
return null;
}
The InteractsWithSchemas
trait is included on the resource pages like so:
ListFoo (your resource class)
-> extends Filament\Resources\Pages\ListRecords
-> extends Filament\Resources\Pages\Page
-> extends Filament\Pages\Page
-> extends Filament\Pages\BasePage
-> uses Filament\Schemas\Concerns\InteractsWithSchemas
In the same trait, Filament uses this method to determine the locale to use when making the translatable content driver:
public function makeFilamentTranslatableContentDriver(): ?TranslatableContentDriver
{
$driver = $this->getFilamentTranslatableContentDriver();
if (! $driver) {
return null;
}
return app($driver, ['activeLocale' => $this->getActiveSchemaLocale() ?? app()->getLocale()]);
}
As you can see, it will fall back to the app’s current locale, since by default getActiveSchemaLocale
will return null.
By using getActiveFormsLocale
– which is deprecated in Filament\Forms\Concerns\InteractsWithForms
but overridden in LaraZeus\SpatieTranslatable\Resources\Concerns\HasActiveLocaleSwitcher
– you can get the functionality back since it uses the $activeLocale
property which is updated when you use the switcher.