Yii 1.1: Simple example for language translation

5 followers

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.

Total 2 comments

#16664 report it
redguy at 2014/03/17 09:34am
Re: Why multiple views?

There are pros and cons of using multiple views: - you can place components differently when dealing with rtl and ltr languages or other language specific view logic - when using opcodecacher - it will be slightly faster (less function calls) - but on the other hand it is harder to maintain

so you must decide on your own whether you go with Yii::t() in your view files or you want separate views for different languages

#16649 report it
Mihai Petrescu at 2014/03/15 05:43am
Why multiple views?

Thank you for the example. But why not just use the translation you have done for translating the other texts in the view too? It would save having multiple views for different languages.

Leave a comment

Please to leave your comment.

Write new article
  • Written by: RKA
  • Updated by: CeBe
  • Category: How-tos
  • Yii Version: 1.1
  • Votes: +1
  • Viewed: 7,801 times
  • Created on: Mar 14, 2014
  • Last updated: Apr 14, 2014
  • Tags: yii, i18n