Example of changing language

Is there any tutorial or step by step example to change language in blog demo or any?

Thanks,

MP

I made a very simple test and it’s OK. Followings are 4 steps to add the support for french language:

1/ Add following line in protected/views/layout/main.php

$lang = $_GET[‘lang’];//Yii::app()->language;

echo $lang.’<br/>’;

Yii::app()->setLanguage($lang);

echo Yii::t(‘blog’,‘Active record class “{class}” does not have a scope named “{scope}”.’);

2/ Create a folder fr or whatever language you like under protected\messages\

3/ Create message file named blog.php in folder protected\messages\fr\ with the content as belows or whatever text that you want to translate.

return array (

‘Active record class “{class}” does not have a scope named “{scope}”.’ => 'La classe Active record « {class} n\‘a pas de scope nommé « {scope} ».’,

);

4/ Change to french language with uri "index.php?lang=fr"

Please refer to http://www.yiiframework.com/doc/guide/topics.i18n for more details.

Nice work.

But this mean thay you must call Yii::t(…).

I want to set to Slovenian language, so all messagess will be writen in my language(of course if i will translate it). I know that i can do this in confing. But this only work if i put translated messages in

yii/framework/messages. But this is not very useful…

I want to use it like you, but without calling Yii::t(…)

Do you know how to do that?

Tnx

Nice. I only have a question: I have looked around without finding an answer: does the message to translate have to be the key? Or can we replace it by an id number or though?

Thanks!

If you do:


Yii::t('test', "example message");

"example message" must be in the language defined over Yii::app()->sourceLanguage. If you set sourceLanguage to something else (eg: xx), you can then provide translation for your original sourceLanguage - "xx" does not exist and is used as a dummy.




Yii::app()->sourceLanguage = 'xx';

Yii::app()->language = 'en';

Yii::t('test', "0001");

You must provide this file: "protected/messages/en/test.php":


return array(

   '0001' => 'example message';

);

So you can basically use placeholders as keys and provide translations for all possible languages.

Smooth hack!! This is actually exactly what I needed and it will make things so much simpler, specially if you modify a bit of your text!

Thanks a lot!

Yes, but take in mind that you can use console command that helps you with translation. At first I wasn’t happy at all with the Yii i18n approach, but now I use it all over. If a message changes (which shouldn’t happen often once you translated a production-ready project) or if you add new messages, you can simply run that console command in order to create a merged translation file (which contains all old messages and changes). Then translate that file, delete the old “en.php” and rename “en.php.merged” to “en.php”. It’s quite simple.

Quand je lit la méthode proposé pour la traduction je deviens FOUUUUU…

When I read the method to translate all the msg i become CRAZYYYY…

I resume … duplicate all the file where there are a msg you need to translate and translate the file in a directory … ALL these think are crazy … why not translate all YII framework and make distrib for each language in the word ??? NO do like linux or other bestseler of the opensource world … crazy … what these bestseler do for the support of ‘i18n’ ???

The base is same:

Yii::t(‘programName’,‘key’);

a dir with the target language ex ‘fr-FR’

But the rest is very different:

in that dir a list of file.txt with the name : programName.txt and inside a list of :

‘key1’=>‘translation’

‘key2’=>‘translation’

Il est 2h20 du matin et je suis vert de rage de decouvrir seulement maintenant le MEGA problème de traduction qu’il y a dans YII framework (moi qui le croyais … presque PARFAIS)

It is 2:20 in the morning and I am green with rage just now discovering the MEGA problem of translation there is in YII framework (which I’m almost near to the perfection …)

I don’t understand your point.

You don’t need one translation file per language and per file where you invoke Yii::t(…).

Yii::t(‘fileName’,‘text to translate’)

If you want, all messages can be translated in one big file if you use the same ‘fileName’ in your whole WebApp.

But don’t be so mean. I’m not sure BTW I get what is your complaint about. Did you read documentation (guide, API…) about message and file translation?

Ok yesterday it was late and i became crazy for nothing, I’m wrong, now tell me pleise what you do step by step to translate these messages yii/framework/validators/CRequireValidator.php in you application:

line 51 : $message=$this->message!==null?$this->message:Yii::t(‘yii’,’{attribute} must be {value}.’

line 58 : $message=$this->message!==null?$this->message:Yii::t(‘yii’,’{attribute} cannot be blank.’);

Regards,

I know how that work: thank to all:

the (system) translation file are in yii\framework\messages\YOUR_LANG\yii.php

To use it, it very simple (of course when we know every thing is easy), simply put these to line in your app:

in the file : yii/myApp/protected/config/main.php add these to line

'sourceLanguage'=&gt;'en',


'language'=&gt;'fr',

and it’s finish :wink: (it’s finish for system message but for private message …, if some body know tel us else, I will write to you, late when I understand myself)

PS: just one thin it was not more simple to add these 4 lines of explanation in the documentation with a simple example and every body understand immediately :slight_smile:

Nevermind I got it to work!

I read a lot of things about language setting, but I can’t find a “clean” way to manage it.

On my site, users can store their spoken language in their profile (in database). I get the user language with :


$language=User::model()->notsafe()->findByPk(Yii::app()->user->id)->profile->language;

I can also store it in a cookie at each login using :


Yii::app()->user->setState('language',$language);

Then, the difficulties begin. My understanding is :

If I want to use Yii localization (to format dates for instance), I need to set Yii::app()->language variable on each client request.

Setting the language in "protected/views/layout/main.php" is quite ugly to me. Is there another way to do it (without defining a new master controller or any other heavy solution) ?

Just want to put this on the right place :


Yii::app()->language=Yii::app()->user->getState('language');

Second difficulty, I want to use the CJuiDatePicker and its language property.

But CJuiDatePicker need ‘fr’ when Yii use ‘fr_fr’, and worst, it need ‘’ for ‘en_us’.

So I can’t use DatePicker this way :


<?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(

    'name'=>'Character[birthday]',

    'value'=>$model->birthday,

    'language'=>Yii::app()->language,

    // additional javascript options for the date picker plugin

    'options'=>array(

	'showAnim'=>'fold',

    ),

    'htmlOptions'=>array(

	'style'=>'height:20px;'

    ),

)); ?>



By the way, DatePicker date format do not match any Yii/i18N format (nor syntax, nor result). I can’t find a way to fill DatePicker input with a stored date correctly formatted (except if I put a hard-coded format).

I think the CJuiDatePicker need a date format "translator" to be usable.

Any convenient solutions or advices are welcome!

Hi jbcrouigneau.

You can see my solution on the yii playground project: here, here and here :blink: ;D

Could you tell me what you think?

…feel free to ask if you have any doubt.

bye,

Giovanni.

Hello, This playGround is a goldmine !!

However, I’ve created the locale file which adds the new date formats under i18n/data, but it doesn’t seem to merge it with the framework’s as i get an error such as ‘small’ is an undefined index.

Any ideas about it ?

Many thanks,

Regards,

xav

Hi all!

I’ve extended my Yii application with CDbMessageSource:


    // application components

    'components' => array(

        'messages' => array(

            'class' => 'CDbMessageSource', /* 02 marzo aggiunto supporto per le lingue */

        ),

It’s all ok, messages are retrieved correctly but … how can i change language without set any parameter in config files?


return array(

    ...

    'language' => 'en',

    ....



ps. I just want to use db stored messages. No files no other stuff. I mean, … something like this…:

Yii::app()->language = $_SESSION[‘lang’]; but … where I have to put this code?

This is a solution:

/protected/views/layouts/main.php now contains:


<?php @session_start(); Yii::app()->setLanguage(isset($_SESSION['lang'])?$_SESSION['lang']:'it'); ?>

at first line.

with "index.php?r=site/changelanguage&lang=it" i can change language.


  public function actionChangelanguage() {

    @session_start();

    $_SESSION['lang'] = (strtolower($_GET['lang']));

    $this->redirect(array('site/index'));

  }

this extension I just created might help you

Cheers,

Gustavo

You are right! I was looking for an example for hours!!

Check out language picker extension in my signature

Here is how I did this…

In short: I attached an event handler to the onBeginRequest behavior and did set the application language within that event handler method. Since the method is called before each request, it is a good place…

Best regards…