I am trying to set the app language of my application using user input. Is it possible to set the language dynamically and globally for the whole application, without using the config? I use the advanced template with separate backend and frontend;
I’ll try to explain my situation: When a user is logged in, I can see from which country he/she is. So I want to check of her language is available for the application. I want everything to be translated. If the translations are not available, I want the application set to default English. In case a language is available, I want to set the available language.
I can set the language using \Yii::$app->language but it only works for the controller I am in at that moment. When I go to a different controller, the language setting is lost. I want it globally in the whole application. How can i do this? Does anyone have a tip for me?
You mean that I need to create a base controller that extends controller and the use my application controller to extend the BaseController? I found similar solutions like that online. Wasn’t sure that was the best way to solve the problem or not.
That is a difficult way to do it because you have to change every controller. Just use the "as beforeRequest" event handler in your configuration and pass it a class like this:
<?php
namespace app\components;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
class LanguageHandler extends \yii\base\Behavior
{
public function events()
{
return [\yii\web\Application::EVENT_BEFORE_REQUEST => 'handleBeginRequest'];
}
public function handleBeginRequest($event)
{
if ( \Yii::$app->getRequest()->getCookies()->has('_lang')
&& array_key_exists(\Yii::$app->getRequest()->getCookies()->getValue('_lang'), \Yii::$app->params['languages']))
{
\Yii::$app->language = \Yii::$app->getRequest()->getCookies()->getValue('_lang');
}
}
}