R
R
ryzhak2014-08-21 16:53:08
Yii
ryzhak, 2014-08-21 16:53:08

How to tie multilingualism in yii2?

Problem: the language does not change when it is changed in the controller, and if you change it directly in the view, the language changes.
In general, I'm trying to fasten multilingualism to yii2. In yii2, the current language changes through: At the moment I have 2 images in the main layout (/view/layouts/main) with links that are present on all pages:
\Yii::$app->language = "ru-RU";

<a id="enLang" href="/site/lang?lang=en"><img src="/images/england.png" class="image-responsive" /></a>
<a id="ruLang" href="/site/lang?lang=ru"><img src="/images/russia.png" class="image-responsive" /></a>

When clicking on the link, we are redirected to the action lang of the site controller. Here we change the language depending on the $_GET['lang'] parameter and redirect the user to the page where he was.
public function actionLang(){
        switch ($_GET['lang']){
            case 'ru':
                \Yii::$app->language = "ru-RU";
                break;
            case 'en':
                \Yii::$app->language = "en-EN";
                break;
        }
        return $this->redirect(Url::previous());
    }

But the language does NOT change. Also, if you change it in layout(view/layouts/main), it doesn't change either. However, if you change it directly in the view, then everything works.
Question: Why doesn't the language change in the controller? How to do it right/beautifully?
Thanks in advance
PS At the moment, it's done like this: when you click on a link with a language, the session is recorded which language the user has chosen and a redirect is made back to the page. And in the view, the code that checks if the lang session variable is not empty, then we change the language . But in each view, adding such code is stupid.
if(!empty(\Yii::$app->session["lang"])){
    \Yii::$app->language = \Yii::$app->session["lang"];
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Zelenin, 2014-08-22
@ryzhak

you load the application instance, getting into actionLang, redefine the language from the config in it, then redirect to another URL, loading a new application instance with a NOT overridden language (language is loaded from the config).
The session hack looks good, but of course it should be tested in a component loaded in the bootstrap.
yiiframework.ru/forum/viewtopic.php?f=19&t=19390 For example, here's a fresh topic on the forum. Look at the examples, follow the links.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question