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

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

If you have a multilingual application, you have to provide the user with a means to select/change the language, and you have to manage the application language in the background.

Here's my way of doing this (see also this post for an alternative):

  • Provide a language selector in the header of each page using a custom widget.
  • When a language is selected, save it in the Session and in a Cookie.
  • Every time a page/url is requested, check if the language is provided (via POST, session or cookie) and set the application language accordingly.
    For this, implement an event handler for the 'onBeginRequest' event. As the name of the event suggests, this event handler then will be called on the beginning of every request.

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 584 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