Setting and maintaining the language in Application (i18n)

You are viewing revision #4 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#5) »

As seen in this post, Yii doesn't enforce how language is set and maintained within the session.

According to that post, the preferred method is to create a base controller which implements code for maintaining the language state. That Controller is then used in your code instead of CControler.

Here's my method of implementing this idea:

components/MyController.php

<?php
class MyController extends CController
{
    function init()
    {
        parent::init();
        $app = Yii::app();
        if (isset($_POST['_lang']))
        {
            $app->language = $_POST['_lang'];
            $app->session['_lang'] = $app->language;
        }
        else if (isset($app->session['_lang']))
        {
            $app->language = $app->session['_lang'];
        }
    }
}
?>

You can use a custom made Widget to let the user select language:

components/LangBox.php

class LangBox extends CWidget
{
    public function run()
    {
        $currentLang = Yii::app()->language;
        $this->render('langBox', array('currentLang' => $currentLang));
    }
}

components/views/langBox.php

<?= CHtml::form() ?>
    <div id="langdrop">
        <?= CHtml::dropDownList('_lang', $currentLang, array(
            'en_us' => 'English', 'is_is' => 'Icelandic'), array('submit' => '')) ?>
    </div>
</form>

19 0
29 followers
Viewed: 163 791 times
Version: Unknown (update)
Category: Tutorials
Written by: olafure
Last updated by: Yang He
Created on: Apr 5, 2009
Last updated: 12 years ago
Update Article

Revisions

View all history

Related Articles