Setting and maintaining the language in Application (i18n)

You are viewing revision #8 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 or see the changes made in this revision.

« previous (#7)next (#9) »

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:

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

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

components/views/langBox.php

<?php echo CHtml::form(); ?>
    <div id="langdrop">
        <?php echo CHtml::dropDownList('_lang', $currentLang, array(
            'en_us' => 'English', 'is_is' => 'Icelandic'), array('submit' => '')); ?>
    </div>
<?php echo CHtml::endForm(); ?>
19 0
29 followers
Viewed: 163 772 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