David
David

Reputation: 4508

yii language localization of mysql table data into view

I have yii language localization turned ON, so I use in config 'language'=>'en', and write things like Yii::t('layouts_main','Home') and store translations of Home in php file. But apart of this, I have tables, and there are data inside in different languages. For example I have a list of countries which must be stored in mysql table in different languages. Table structure is very simple: id, name_en,name_de,name_es etc... I did it that way so if language change those 2 letters must be controlling from which sell to read the name.

In my controller I get my data from table to array

$tableCountry = Country::model()->findAll();

Then I'm making such variable which will containt "name+" language variable which is 'en' in config $name_lang ="name_".Yii::app()->Language;

So now I made variable $name_lang which contains name_en

Then I choose the right sells using $name_lang variable

$list=CHtml::listData($modelCountry,'id',$name_lang);

Using $name_lang only name_en data will go to List. So later I can switch settings of language in config file to "de" and only name_de data will fgo to List.

So everything is fine here. But what If I have complex table which contains country_name_en, city_name_en,region_name_en etc...

To put this data into list I have to make 3 or more variables

$country_name_lang ="country_name_".Yii::app()->Language;

$city_name_lang ="city_name_".Yii::app()->Language;

$region_name_lang ="region_name_".Yii::app()->Language;

So I wonder is there any other better way to do such things ?

Upvotes: 0

Views: 216

Answers (1)

Mihai P.
Mihai P.

Reputation: 9357

Option 1: You can define in the model another variable called country_name (without any suffix). You can do this just in the model, you do not have to create a field in the db too. No need for validation or anything for this variable. Then in your after find method for the model you can do

public function afterFind()
{
    $this->country_name = $this->{"country_name_".Yii::app()->Language};
}

Feel free to add everything here.

Now everywhere you should be able to use $model->country_name without any care what the language is.

Option 2 would be to use magic methods. you can read more from them here: http://www.php.net/manual/en/language.oop5.magic.php Define for your model such a method:

public function __call($name, $arguments)
{
    if(isset($this->{$name. "_".Yii::app()->Language})) 
        return $this->{$name. "_".Yii::app()->Language}
    elseif(isset($this->$name))
        return $this->{$name}
    else 
        throw new Exception(xxx, 'We couldn\'t find the variable');
}

Now you should be able to use $model->country_name() and you would again get the variable in the proper language. You can use also $model->id() and you would get the proper id too as it has a fallback if there is no id_en field.

Upvotes: 3

Related Questions