Cannot set default locale with language switcher
What steps will reproduce the problem?
My default locaal is 'de'.
What is the expected result?
An url without 'de'
What do you get instead?
An url with 'de'
Additional info
I have this language switcher:
<li>
<a href="#."><?= $translator->translate('menu.language') ?></a>
<ul>
<li><a href="<?= $urlGenerator->generateFromCurrent(['_language' => 'en'], fallbackRouteName: 'home') ?>">English</a></li>
<li><a href="<?= $urlGenerator->generateFromCurrent(['_language' => 'de'], fallbackRouteName: 'home') ?>">Deutsch</a></li>
<li><a href="<?= $urlGenerator->generateFromCurrent(['_language' => 'nl'], fallbackRouteName: 'home') ?>">Nederlands</a></li>
<li><a href="<?= $urlGenerator->generateFromCurrent(['_language' => 'fr'], fallbackRouteName: 'home') ?>">Français</a></li>
</ul>
</li>
my config params.php
'app' => [
'charset' => 'UTF-8',
'locale' => 'de',
'name' => 'My Project',
],
'yiisoft/aliases' => [
'aliases' => require __DIR__ . '/aliases.php',
],
'yiisoft/translator' => [
'locale' => 'de',
'fallbackLocale' => 'de',
'defaultCategory' => 'app',
],
If I call my website url without language the german website is show as expected. If I switch to English the german website is shown again without 'en'. (website) If I switch to German the german website is shown but with the 'de' (website/de)
| Q | A |
|---|---|
| Version | 1.0.? |
| PHP version 8.1 | |
| Operating system | Windows 11 |
Likely that's the issue of Locale middleware.
Actually... have you configured it?
params.php
'yiisoft/translator' => [
'locale' => 'de',
'fallbackLocale' => 'de',
'defaultCategory' => 'app',
],
With other words. I cannot switch to English language.
sourceLocale is always 'en' (How can i change this).
If i choose English the handle function in
src\EventHandler\SetLocaleEventHandler.php
is not called
final class SetLocaleEventHandler
{
public function __construct(
private TranslatorInterface $translator,
private WebView $webView
) {
}
public function handle(SetLocaleEvent $event): void
{
$this->translator->setLocale($event->getLocale());
$this->webView->setLocale($event->getLocale());
}
}
Are you using Locale middleware? Could you show its config?
Yes,
config\web\params.php
<?php
declare(strict_types=1);
use Yiisoft\ErrorHandler\Middleware\ErrorCatcher;
use Yiisoft\Router\Middleware\Router;
use Yiisoft\Session\SessionMiddleware;
use Yiisoft\Yii\Middleware\Locale;
return [
'middlewares' => [
ErrorCatcher::class,
SessionMiddleware::class,
Locale::class,
Router::class,
],
'locale' => [
'locales' => ['de' => 'de-DE', 'en' => 'en-US', 'nl' => 'nl-NL', 'fr' => 'fr-FR'],
'ignoredRequests' => [
'/debug**',
],
],
];