Welcome Guest, Not a member yet? Register   Sign In
setLocale not working as I intended?
#1

I'm trying to make a multilingual website. I've looked at various tutorials and websites but none is giving me the advice I needed.
I've been able to set the localization working with the auto-detection
PHP Code:
$negotiateLocale true;  

However I'm trying to give the user the ability to change language in his user profile. Language is saved on database user table and retrieved during login as variable
PHP Code:
$user['language'
.
After login I call this function to set the user locale:
PHP Code:
service('language')->setLocale($user['language']); 

I expect that now the Locale is the one the user has chosen, and not the default one. If I check with
PHP Code:
service('language')->getLocale(); 

I always get the default language (i.e. "en") instead of the chosen one (i.e. "it"), even if $negotiateLocale is changed to false.

Note that user language choices are correctly included in the supportedLocales array.

I'd like to avoid to use the routing method with {locale} placeholder, because I'll have to rework a big part of the website and update all the links by adding the language segment.

any ideas why Locale is not updated globally on the app by using setLocale?

thanks in advance
Reply
#2

It is wired, because
Code:
Language::setLocale()
is a just setter.
https://github.com/codeigniter4/CodeIgni...ge.php#L70
Reply
#3

Did you set this?

PHP Code:
public $supportedLocales = ['en']; 
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#4

(03-04-2022, 01:39 AM)InsiteFX Wrote: Did you set this?

PHP Code:
public $supportedLocales = ['en']; 


yep

PHP Code:
public $supportedLocales = ['it','en','bs']; 
Reply
#5

(This post was last modified: 03-04-2022, 03:32 AM by Mano.)

(03-03-2022, 06:12 PM)kenjis Wrote: It is wired, because
Code:
Language::setLocale()
is a just setter.
https://github.com/codeigniter4/CodeIgni...ge.php#L70

Sorry I don't understand your answer. It means it is not working as a global variable?
should I set it in every controller?

ok, it seems I've found the solution.
At login or change password, I store the language variable ('it','en',etc...) into a session variable

PHP Code:
session()->set('user_language',$data['language']); 

then on BaseController.php i put this line:

PHP Code:
if (session()->get('user_language')){
    service('language')->setLocale(session()->get('user_language'));


now every page is correctly translated according to user selected language (that is stored into database user table and recovered at login). If session is not existing (i.e. user not logged in), pages are displayed with default language.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB