setLocale not working as I intended? - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28) +--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30) +--- Thread: setLocale not working as I intended? (/showthread.php?tid=81449) |
setLocale not working as I intended? - Mano - 03-03-2022 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 RE: setLocale not working as I intended? - kenjis - 03-03-2022 It is wired, because Code: Language::setLocale() https://github.com/codeigniter4/CodeIgniter4/blob/fb4707e2be4796352d92ef72f91e41921311aa5f/system/Language/Language.php#L70 RE: setLocale not working as I intended? - InsiteFX - 03-04-2022 Did you set this? PHP Code: public $supportedLocales = ['en']; RE: setLocale not working as I intended? - Mano - 03-04-2022 (03-04-2022, 01:39 AM)InsiteFX Wrote: Did you set this? yep PHP Code: public $supportedLocales = ['it','en','bs']; RE: setLocale not working as I intended? - Mano - 03-04-2022 (03-03-2022, 06:12 PM)kenjis Wrote: It is wired, because 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')){ 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. |