2014-03-14

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.

Step 2:
Modify the model with category information

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

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

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

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

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

Show more