How to user an application behavior for maintain runtime configuration

You are viewing revision #1 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 (#2) »

In this tutorial will be explained a method for manage some configuration runtime. This excellent tutorial follows a similar approach, but requires to write a masterclass wich all controllers are supposed to extend, following this wiki you can achive the same editing only the configuration.

This is often needed for manage internationalization, themes and other confugration that depends from the user.

The most confortable way is to user an application behavior. In this example we save the language in the session, but can also be saved in database.

Create a file in compoments named ApplicationConfigBehavior and copy this code in it:

 * ApplicationConfigBehavior is a behavior for the application.
 * It loads additional config paramenters that cannot be statically 
 * written in config/main
class ApplicationConfigBehavior extends CBehavior
     * Declares events and the event handler methods
     * See yii documentation on behaviour
    public function events()
        return array_merge(parent::events(), array(
     * Load configuration that cannot be put in config/main
    public function beginRequest()
       if (isset($_POST['lang']))
               $this->owner->user->setState('applicationLanguage', $_POST['lang']);
       if ($this->owner->user->getState('applicationLanguage'))

This file must be included in config/main.php:

'behaviors' => array('ApplicationConfigBehavior')

For update the language we can use a widget (to be included in layout/main), for example:


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