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

changed
Title
How to useuser 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 tofor 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
whichwich all controllers are supposed to extend,
following this wiki you can achieveachive the same by
only editing only the configuration.

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


The most comfortableconfortable 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 componentscompoments named
ApplicationConfigBehavior and copy this code:code in it:
~~~
[php]
<?php
 
/**
 * ApplicationConfigBehavior is a behavior for the application.
 * It loads additional config parametersparamenters that
cannot be statically 
 * written in config/main
 */
class ApplicationConfigBehavior extends CBehavior
{
    /**
     * Declares events and the event handler methods
     * See yii documentation on behaviorbehaviour
     */
    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')
~~~


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