Simple example for language translation

Language translation is a common requirement in multi lingual sites. In Yii, we can translate using message and view translation.

Message translation is done as Yii::t(category,message) in simplest form. Create PHP translation files as protected/messages/LocaleID/CategoryName.php. The file simply contains message translations returned in array format. The built in validation messages for form fields are automatically converted by the framework in most cases.

For File translation, the file with same name under the LocaleId sudbirecotry is created. If not found, the default file is selected.

One of the issues encountered was that the language state was not maintained in subsequent request. To overcome that, we use an application behavior. Refer http://www.yiiframework.com/wiki/208/how-to-use-an-application-behavior-to-maintain-runtime-configuration/ for more details. Below , shows a simple example to convert the yii default login page to french storing the language in cookie.

Step 1: Create the login.php (login is the category name used) file under /protected/messages/fr which returns the array.

<?php 
return array(
				'Login'=>'Se connecter',
				'Username'=>'Nom d\'utilisateur',
				'Password'=>'Mot de passe',
			    'Remember me next time'=>'Se souvenir de moi',
				'Fields with * are required.'=>"Les champs marqués d'une * sont obligatoires.",
				"Please fill out the following form with your login credentials"=>"S'il vous plaît remplir le formulaire ci-dessous avec vos informations de connexion:",
				'Login'=>'Connexion',
			);
?>

Step 2: Modify the model with category information

public function attributeLabels()
	{
		return array(
			'rememberMe'=>Yii::t('login','Remember me next time'),
			'username' =>Yii::t('login','Username'),
			'password' =>Yii::t('login','Password'),				
		);
	}

Step 3: Create the new view file for french under /protected/views/site/fr/login.php

<?php
/* @var $this SiteController */
/* @var $model LoginForm -French*/
/* @var $form CActiveForm  */

$this->pageTitle=Yii::app()->name . ' - Login';
$this->breadcrumbs=array(
	'Login',
);
?>

<h1><?php echo Yii::t('login','Login');?></h1>
<?php echo CHtml::link('Fr',array('Site/Trans','langChange'=>'fr'))?>
<?php echo "----";?>
<?php echo CHtml::link('Eng',array('Site/Trans','langChange'=>'en'))?>
<p>S'il vous plaît remplir le formulaire ci-dessous avec vos informations de connexion::</p>

<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'login-form',
	'enableClientValidation'=>true,
	'clientOptions'=>array(
		'validateOnSubmit'=>true,
	),
)); ?>

	<p class="note">Les champs marqués d'une * sont obligatoires</p>

	<div class="row">
		<?php echo $form->labelEx($model,'username'); ?>
		<?php echo $form->textField($model,'username'); ?>
		<?php echo $form->error($model,'username'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'password'); ?>
		<?php echo $form->passwordField($model,'password'); ?>
		<?php echo $form->error($model,'password'); ?>
		<p class="hint">
			Astuce: Vous pouvez vous connecter avec demo / demo ou admin / admin.
		</p>
	</div>

	<div class="row rememberMe">
		<?php echo $form->checkBox($model,'rememberMe'); ?>
		<?php echo $form->label($model,'rememberMe'); ?>
		<?php echo $form->error($model,'rememberMe'); ?>
	</div>

	<div class="row buttons">
		<?php echo CHtml::submitButton( Yii::t('login','Login')); ?>
	</div>

<?php $this->endWidget(); ?>
</div><!-- form -->

Have added two links on the top to switch the languages.

Step 4: In order to maintain the state, modify the main as follows.

'behaviors' => array('ApplicationConfigBehavior')

Step 5: Include the codeset of behaviour classs and store the language in cookie.

<?php
/**
 * 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(
            'onBeginRequest'=>'beginRequest',
        ));
    }
 
    /**
     * Load configuration that cannot be put in config/main
     */
    public function beginRequest()
    {
        if (isset(Yii::app()->request->cookies['pref_lang']))
          $this->owner->language= Yii::app()->request->cookies['pref_lang']->value; //set a language for each request
        else 
            $this->owner->language='en';
    }
}

That's it, run the application and see the switching of languages.

1 0
5 followers
Viewed: 37 333 times
Version: 1.1
Category: How-tos
Tags: i18n, Yii
Written by: RKA
Last updated by: CeBe
Created on: Mar 14, 2014
Last updated: 9 years ago
Update Article

Revisions

View all history

Related Articles