i18n for your model in just 1 line

You are viewing revision #5 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 or see the changes made in this revision.

« previous (#4)next (#6) »

A simple trick to get the localized version of a model field is to add this little method to your models.

[...]
public function getNameLocalized()
{
    return Yii::t(strtolower(__CLASS__), $this->name);
}

What this snipped does is, that it looks for a translation with your model name (in lowercase) as category and the database entry as the translation key.

Just one simple example:

Imagine you have a country table (and a model called Country)

  ID  |  NAME
------|--------
   1  |  sweden
   2  |  italy
   3  |  norway
------|--------

Use any of the offered translation methods. I simply use php-files in the `protectec/messages` folder.

Let's assume the language is set to `'de'`. The translation file would look like that:

protected/messages/de.php:

<?php
return array(
    'sweden' => 'Schweden',
    'italy'  => 'Italien',
    'norway' => 'Norwegen',
);

Now this is the fun part where PHP5 unfolds its magic (functions): To easily create a localized drop down list where your visitor can select a country you only need this simple line of php code in your view:

<?php
echo CHtml::activeDropDownList($model, 'country_id', 
     CHtml::listData(Country::model()->findAll(), 'id', 'nameLocalized'))
?>

This creates this kind of HTML-Code:

``

<option value="1">Schweden</option>
<option value="2">Italien</option>
<option value="3">Norwegen</option>

``

I hope this helps you saving time. If you have any suggestions just drop a comment.

12 0
9 followers
Viewed: 19 853 times
Version: Unknown (update)
Category: Tutorials
Tags: i18n
Written by: mintao
Last updated by: Orteko
Created on: Feb 16, 2010
Last updated: 14 years ago
Update Article

Revisions

View all history

Related Articles