Setting and maintaining the language in Application (i18n)

You are viewing revision #10 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#9)

  1. See also
  2. Links

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(); ?>

See also

  • Here is another approach using behaviors.

Links

19 0
29 followers
Viewed: 163 773 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