Difference between #2 and #1 of How to use an application behavior to maintain runtime configuration

changed
Title
How to useruse an application behavior for maintain
runtime configuration
unchanged
Category
How-tos
unchanged
Tags
application, configuration, behavior
changed
Content
In this tutorial will be explained a method forto manage
some configuration runtime. [This excellent
tutorial](http://www.yiiframework.com/wiki/26/setting-and-maintaining-the-language-in-application-i18n
"") follows a similar approach, but requires to write a masterclass
wichwhich all controllers are supposed to extend,
following this wiki you can achiveachieve the same
editingby only editing the configuration.

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


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

Create a file in compomentscomponents named
ApplicationConfigBehavior and copy this code in it:code:
~~~
[php]
<?php
 
/**
 * ApplicationConfigBehavior is a behavior for the application.
 * It loads additional config paramentersparameters that
cannot be statically 
 * written in config/main
 */
class ApplicationConfigBehavior extends CBehavior
{
    /**
     * Declares events and the event handler methods
     * See yii documentation on behaviourbehavior
     */
    public function events()
    {
        return array_merge(parent::events(), array(
            'onBeginRequest'=>'beginRequest',
        ));
    }
 
    /**
     * 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->owner->language=$this->owner->user->getState('applicationLanguage');
        else 
            $this->owner->language='en';
    }
}
~~~


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

~~~
[php]
'behaviors' => array('ApplicationConfigBehavior')
~~~


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


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

**components/views/langBox.php**
~~~
[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(); ?>
~~~