PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 15, 2022

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

 March 15, 2022     cakephp, cakephp-3.0, internationalization, php, translate     No comments   

Issue

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.



Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing