Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set global language value in Yii2 application

Where can I set language (based on user's cookie) globally? How to make it work in the whole application (controllers,views, etc.) ?

In documentation I found \Yii::$app->language = ''; but, where I can write my logic to change the language in right way?

like image 444
bxN5 Avatar asked Jan 10 '15 22:01

bxN5


2 Answers

You can set your base language in the configuration file. In the basic application it's default location is: /config/web.php, in advanced: application-name/config/main.php and application-name/config/main-local.php.

$config = [
    'id' => 'basic',
    'language' => 'nl', // Set the language here
    'basePath' => dirname( __DIR__ ),
    'bootstrap' => ['log'],
    ...
];
like image 61
Jelmer Keij Avatar answered Sep 21 '22 17:09

Jelmer Keij


You should use

\Yii::$app->language = ''; 

inside the controller that is parent to all your controllers. The parent class should be inside the components folder, and if it is not available than create the component with something like

use yii\web\Controller;
class MyController extends Controller
{
    public function init()
    {
        parent::init();
        #add your logic: read the cookie and then set the language
    }
}

After that, you have to be sure that all your controllers extends your newly created MyController instead of the original one.

I hope it helps.

like image 43
Masiorama Avatar answered Sep 21 '22 17:09

Masiorama