Search code examples
phpcakephpinternationalizationcakephp-3.0translate

CakePHP 3.5 Translate behavior I18n::getDefaultLocale() changes by itself


I am using CakePHP 3.5. When My browser is in english, enverything is fine. The default locale is en_US, as I set it, and I can display content in french if I set the locale to fr_CA (I18n::setLocale('fr_CA'))

But when I change my browser's language to fr_CA, it somehow changes the default locale as well to fr_CA. So the website displays in french, but the content still displays in english since it is now the default locale

Setting the default locale in config\app.php

'App' => [
    'namespace' => 'App',
    'encoding' => env('APP_ENCODING', 'UTF-8'),
    'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
    .....
],

Adding the valid locales in src\Application.php

$middlewareQueue->add(new LocaleSelectorMiddleware(['en_US', 'fr_CA']));

Adding the Translate behavior in ArticlesTable.php

$this->addBehavior('Translate', [
    'fields' => ['name', 'slug'],
    'allowEmptyTranslations' => false,
]);

Fetching the content in ArticlesController.php

$query = $this->Articles->find('all')
    ->where(['Articles.name !=' => ''])
    ->contain(['Media' => function ($q) {
        return $q->find('medium');
}]);

When my browser is in english (en_US) and I echo I18n::getDefaultLocale()

'en_US'

When it's in french (fr_CA) and I echo I18n::getDefaultLocale();

'fr_CA'

Note that I updated to CakePHP 3.5 recently and followed the guide to add the Middleware: Adding the new HTTP Stack to an Existing Application


Solution

  • That's a bug that will be fixed in the next release (3.5.3).

    See https://github.com/cakephp/cakephp/pull/11200

    Until this is fixed you can either apply the patch locally on own your own, or manually invoke \Cake\I18n\I18n::getDefaultLocale() once in your bootstrap so that the default locale is being stored before the modifications of the locale selector are being aplied.