Manage (Target) Language in Multilingual Applications + A Language Selector Widget (i18n)

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

« previous (#6)

In case of a multilingual application, one might consider it a reasonable approach to store the preferred language of the user in a session variable, and after that, every time a page is requested, to check this session variable and render the page in the indicated language. This tutorial shows a Yii-way of doing this.
We implement an event handler for the onBeginRequest event; as the name of the event suggests, this event handler will be called at the beginning of each request, so its a good place to check whether a language is provided (via post, session or cookie) and set the application language accordingly.
We also implement a simple Language-Selector Widget, which can render the language options as ajax-links or as a drop-down list.

See also this post for an alternative.

Why is it necessary to set the application language for every request?


--->The requested page will be shown in the target language of the application, which can be set/get via Yii::app()->language.
--->If this property is not set explicitly, Yii assumes it to be equal to the source language of the application, which can be set/get via Yii::app()->sourceLanguage and defaults to 'en_us'.
--->These properties can also be set in the main config file, like
'sourceLanguage'=>'en',
'language'=>'de',
--->But hardcoding the target language in the main config file is not an option if you have multiple target languages. Therefore we store the current language in the session, and on the beginning of each request set the target language explicitly, like
Yii::app()->language = Yii::app()->user->getState('_lang').

Now to the implementation...


'components/widgets/LanguageSelector.php':

class LanguageSelector extends CWidget
{
    public function run()
    {
        $currentLang = Yii::app()->language;
        $languages = Yii::app()->params->languages;
        $this->render('languageSelector', array('currentLang' => $currentLang, 'languages'=>$languages));
    }
}

I set the available languages in the main config file (see below) and retrieve it here via Yii::app()->params->languages.


'components/widgets/views/languageSelector.php':

<?php echo CHtml::form(); ?>
    <div id="language-select">
        <?php 
		if(sizeof($languages) < 4) {
			$lastElement = end($languages);
			foreach($languages as $key=>$lang) {
				if($key != $currentLang) {
					echo CHtml::ajaxLink($lang,'',
						array(
							'type'=>'post',
							'data'=>'_lang='.$key.'&YII_CSRF_TOKEN='.Yii::app()->request->csrfToken,
							'success' => 'function(data) {window.location.reload();}'
						),
						array()
					);
				} else echo '<b>'.$lang.'</b>';
				if($lang != $lastElement) echo ' | ';
			}
		}
		else {
			echo CHtml::dropDownList('_lang', $currentLang, $languages,
				array(
					'submit' => '',
					'csrf'=>true,
				)
			); 
		}
		?>
    </div>
<?php echo CHtml::endForm(); ?>

If the number of available languages is smaller than four, the languages are displayed as ajax-links, separated with a '|'. When clicked, an ajax-request of type 'post' is sent to the current URL and the page is reloaded in case of success (so it is displayed in the newly selected language). Note that I have to send the 'YII_CSRF_TOKEN' in the request, because I have CSRF Validation for cookies enabled in my config file (see below).
If the number of languages is four or more, a dropDownList is generated.
You can of course always use a dropDownList if you prefer.


'views/layouts/main.php'
Put the widget inside the <div id="header">...</div>:

<div  id="language-selector" style="float:right; margin:5px;">
	<?php 
		$this->widget('application.components.widgets.LanguageSelector');
	?>
</div>


'config/main.php'
(add the following lines to the file, don't replace its contents):

return array(
	'sourceLanguage'=>'en',

	// Associates a behavior-class with the onBeginRequest event.
	// By placing this within the primary array, it applies to the application as a whole
	'behaviors'=>array(
		'onBeginRequest' => array(
			'class' => 'application.components.behaviors.BeginRequest'
		),
	),

	// application components
	'components'=>array(
		'request'=>array(
			'enableCookieValidation'=>true,
			'enableCsrfValidation'=>true,
		),
                // ...some other components here...
	),
	// application-level parameters
	'params'=>array(
		'languages'=>array('tr'=>'Türkçe', 'en'=>'English', 'de'=>'Deutsch'),
	),
);


'components/behaviors/BeginRequest.php'

<?php
class BeginRequest extends CBehavior {
	// The attachEventHandler() mathod attaches an event handler to an event. 
	// So: onBeginRequest, the handleBeginRequest() method will be called.
	public function attach($owner) {
		$owner->attachEventHandler('onBeginRequest', array($this, 'handleBeginRequest'));
	}
	
	public function handleBeginRequest($event) {		
		$app = Yii::app();
		$user = $app->user;
		
		if (isset($_POST['_lang']))
        {
            $app->language = $_POST['_lang'];
			$app->user->setState('_lang', $_POST['_lang']);
			$cookie = new CHttpCookie('_lang', $_POST['_lang']);
			$cookie->expire = time() + (60*60*24*365); // (1 year)
			Yii::app()->request->cookies['_lang'] = $cookie;
        }
        else if ($app->user->hasState('_lang'))
            $app->language = $app->user->getState('_lang');
		else if(isset(Yii::app()->request->cookies['_lang']))
			$app->language = Yii::app()->request->cookies['_lang']->value;
	}
}


That's it.
If something is unclear, wrong or incomplete, please let me know.

9 0
19 followers
Viewed: 50 581 times
Version: Unknown (update)
Category: Tutorials
Written by: c@cba
Last updated by: c@cba
Created on: Dec 25, 2011
Last updated: 12 years ago
Update Article

Revisions

View all history

Related Articles