Setting and maintaining the language in Application (i18n)

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 (by defing your classes with "class ... extends MyController")

Here's my method of implementing this idea:


class MyController extends CController
    function 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:


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


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

See also

  • Here is another approach using behaviors.
19 0
Viewed: 124 658 times
Version: 1.1
Category: Tutorials
Written by: olafure
Last updated by: Yang He
Created on: Apr 5, 2009
Last updated: 11 years ago
Update Article


View all history

Related Articles