Multilingual models

I have the same problem with related models. I will wait your post. ;)

I’m attaching the MultilingualBehavior I was talking about:

2268

MultilingualBehavior.php

So, imagine you have the models News and Section, where a News belongs to a Section, and also you have created the models NewsLang and SectionLang.

You define the following relations in News:




//News.php

public function relations() {

  return array(

    'section'=> array(self::BELONGS_TO, 'Section', 'section_id'),

    'i18nNews' => array(self::HAS_MANY, 'NewsLang', 'news_id', 'on'=>"i18nNews.lang_id='".Yii::app()->language."'", 'index'=>'lang_id'),

    'multilang' => array(self::HAS_MANY, 'NewsLang', 'news_id', 'index' => 'lang_id'),			

  );

}



And for Section:




//Section.php

public function relations() {

  return array(

    'i18nSection' => array(self::HAS_MANY, 'SectionLang', 'section_id', 'on'=>"i18nSection.lang_id='".Yii::app()->language."'", 'index'=>'lang_id'),

    'multilang' => array(self::HAS_MANY, 'SectionLang', 'section_id', 'index' => 'lang_id'),

  );

}



Then you use the behavior as following:




//News.php

public function behaviors() {

  return array(

    'ml' => array(

      'class' => 'application.components.MultilingualBehavior',

      'primaryLang' => Yii::app()->params['primaryLang'], //your main language

      'languages' => Yii::app()->params['translateLangs'], //your translated languages

      'localizedAttributes' => array('title', 'intro', 'content'),

      'relName1' => 'i18nNews',

      'relName2' => 'multilang',

    ),

  );

}






//Section.php

public function behaviors() {

  return array(

    'ml' => array(

      'class' => 'application.components.MultilingualBehavior',

      'primaryLang' => Yii::app()->params['primaryLang'], //your main language

      'languages' => Yii::app()->params['translateLangs'], //your translated languages

      'localizedAttributes' => array('name'),

      'relName1' => 'i18nSection',

      'relName2' => 'multilang',

    ),

  );

}



I realize the parameter names relName1 and relName2 are not very self-explanatory: relName1 refers to the relation name used to get attributes in the current language, and relName2 refers to the relation name used to get attributes in all languages (this will mainly be used in the back-end in order to enter translations for a model).

When working with related models, the thing to keep in mind is to give unique names to the translate relations that will be used together (i18nNews and i18nSection in this case), otherwise they will get mixed in the generated query.

Now, you can retrieve translated news with sections, for example with the following scopes:




//Section.php

public function localized() {

  $this->getDbCriteria()->mergeWith(array(			

    'with'=>'i18nSection',

  ));

  return $this;

}


===========================


//News.php

public function localized() {

  $this->getDbCriteria()->mergeWith(array(

    'with'=>array(

      'i18nNews'=>array(),

      'section'=>array('scopes'=>array('localized')),

    ),

  ));

  return $this;

}



In News controller:




$rs = News::model()->localized()->findAll();



In News view:




foreach ($rs as $r) {

  echo $r->title; //localized news title

  echo $r->section->name; //localized section name

}



NOTE: for the model to be able to find the virtual fields provided by the behavior in its “multilang” mode, you’ll have to add the following to the models (News.php and Section.php in the example):




public function __get($name) {

  try { return parent::__get($name); } 

  catch (CException $e) {

    if ($this->hasLangAttribute($name))	return $this->getLangAttribute($name);

    else throw $e;

  }							

}


public function __set($name, $value) {

  try { parent::__set($name, $value); } 

  catch (CException $e) {

    if ($this->hasLangAttribute($name)) $this->setLangAttribute($name, $value);

    else throw $e;

  }					

}



The reason is that models currently don’t have a way to check if a missing attribute can be obtained through a behavior’s magic getter/setter. This is also the main reason why I first wrote this as a CActiveRecord subclass instead of a behavior. But I prefer to have it as a behavior, even with this inconvenience.

@guillemc:

Thank you so much for posting this!

Could you just add some information regarding the database structure you use?

In your original extension you describe using 2 tables (one with the main language fields and one with all other languages), but I get the idea you’re using all languages (including the fallback one) in the NewsLang table and only general (non-translatable) information (I assume) in the News table.

Is this correct?

@Avalon:

No, I’m still using the same database structure (all attributes in the main table, plus translatable attributes in a separate table).

The reason is that it makes it a lot easier to handle missing translations. Having a default or main language allows you to easily fall back to that language in case a translation doesn’t exist, without having to make another query.

Also, in my experience it matches the way most multilingual sites work. They might start as single language sites, or maybe already plan to be multilingual, but almost always they start entering content in the main language, and translations are added afterwards.

@guillemc:

Thanks for your post. I use it.

I have other problem with CActiveDataProvider().

Can you help me, how to use this extension or your method with related model.

I need, to retrieve all News data with their Sections (with translations).

Thanks, and i`m sorry for my english.

@guillemc:

Thanks for your fast reply. Would there be any way to adapt your behaviour to allow my kind of db scheme? (one table for non-translatable stuff, the other for all languages)

Right now I’m using the translation behaviour created by Schmunk ( github.com/schmunk42/p3extensions/blob/master/behaviors/P3TranslationBehavior.php ), but that doesn’t allow translating entire models; only specific fields of a model.

If you have any ideas or pointers on how to combine the best of these both worlds, that would be absolutely great!

@Samir:

I haven’t tried, but CActiveDataProvider takes a CDbCriteria object as a parameter. So, if you pass it a criteria object that selects also the related language tables (using “with” or “scopes”, what you prefer) then it all should work. What I mean is that you should pass CActiveDataProvider the same criteria that you pass to a findAll() call in order to get the translations.

@Avalon:

The behavior I’m using expects the main model to have the main attributes defined, so that you can call $news->title, and get the title in the current language. But you could define these placeholder attributes directly in the model, instead of the database. So, in your News model, you’d define the attributes:




public $title;

public $intro;

public $content;

...



This would allow you to continue using $news->title and get the translated title, even if the title field doesn’t exist in the news table.

But doing this means you won’t have the fallback value. If the title translated in the current language does not exist you will get a blank title…

Thanks guillemc, for your help :slight_smile:

If I understand correctly, I could fill those attributes up with the current language first, check if they’re empty and use a fallback language when necessary. Is there any drawback to this method (except for the extra query)?

I guess it would be better to query both languages at the same time (current and fallback) - and have the code figure out which one to use - or using a query that will select the right values at once?

Something like:


SELECT o.id

     , o.type

     , o.code

     , o.position

     , ifnull(t.name,d.name) name

     , ifnull(t.description,d.description) description

  FROM base_material o

       INNER JOIN base_material_i18n d

               ON ( o.id=d.base_material_id)

       LEFT OUTER JOIN base_material_i18n t

                    ON ( d.base_material_id=t.base_material_id AND t.localization_id='nl' )

 WHERE d.localization_id='en'

I don’t think I follow you. You could make a query like that, but the purpose of all this was to avoid having to do it. Just by declaring relations and using a behavior you should be able to get the data in the right language.

What I was trying to say is that if you don’t want to have the name and description attributes on the main table, you don’t have to. You can declare them as public properties of your model, and let the behavior populate them with the right data coming from the translations table.

But I think you are right in that you could get current and fallback languages in the same query. I’d try to define a relation with the i18n table like this:




'i18n' => array(self::HAS_MANY, 'ModelLang', 'model_id', 'on'=>"i18n.lang_id='".Yii::app()->language."' OR  i18n.lang_id='".Yii::app()->params['defaultLanguage']."'", 'index'=>'lang_id'),



Then, in the behavior’s afterFind() method, you would check for those translations, and set the main model attribute to either of the two (the current language if it exists, the fallback otherwise).

Don’t worry, guillemc, I’m pretty sure I was the one not following you instead of the other way around :wink:

Thanks for the detailed explanation! I’ll try it out asap :slight_smile:

@guillemc

hi i use your behavior and follow your instruction to enable multilingual in content. but i get error, the error says


Relation "i18n" is not defined in active record class "Section".

also i attach my simple test project and screen shoot for the error with this.

could you help me please.

many thanks :)

nb: sorry for my bad english

Sorry, I made a mistake in my example. In Section model, the “localized” scope should use the relation “i18nSection”, not “i18n”, since that’s the relation name we have defined in the model. (You can use whatever name you want for the relation, just make sure you use the same name in the scope).




//Section.php

public function localized() {

  $this->getDbCriteria()->mergeWith(array(                      

    'with'=>'i18nSection',

  ));

  return $this;

}



Thanks for your fast reply i’ll try it. should i create two table for each model. like news for News model and news_lang for NewsLang model. sorry i’m new bie :D

thanks again ::)

Hi! Thank you for that nice behavior. I start to use it now, but I can’t figure out, how can I reate CRUD for create translations.

Can anybody help me out with this?

I’ve created inputs in my views like this:




<div class="row">

	<?php echo $form->labelEx($model,'title'); ?>

	<?php echo $form->textField($model,'title',array('maxlength'=>50)); ?>

	<?php echo $form->textField($model,'title_hu',array('maxlength'=>50)); ?>

	<?php echo $form->textField($model,'title_en',array('maxlength'=>50)); ?>

</div>



When I post the form, I got these errors:

Failed to set unsafe attribute "title_hu".

Failed to set unsafe attribute "title_en".

You should create rules for those attributes, as if they were attributes from the model itself. Better if you use params instead of hardcoding them, something like:




public function rules() {

	$rules = array(

		array('title', 'required'),

		array('title', 'length', 'max' => 80),

		array('content', 'safe'),			

		array('id, title', 'safe', 'on' => 'search'),

	);

	foreach (Yii::app()->params['translateLangs'] as $k => $v) {

		$rules[] = array('title_'.$k, 'length', 'max' => 80);

		$rules[] = array('content_'.$k, 'safe');

	}

	return $rules;

}



Thanks for the help, guillemc!

You probably want to add a __isset magic overload as well:




public function __isset($name){

  if (! parent::__isset($name)) {

    return ($this->hasLangAttribute($name));

  } else {

    return true;

  }

}



I haven’t tested it yet, but something along those lines will do.

I also have suggestions for better names for relName1 and relName2: localizedRelation and multilangRelation

As a final thought, the point where you create $this->langForeignKey from $owner->tableName() is broken if tableName returns a string containing the database name (e.g. ‘mydb.products’)

You can replace




$owner->tableName()



with




array_pop(explode('.',$owner->tableName()))



to achieve that extra compatibility.

But those are all small points. All in all, this multilang stuff is really useful.

Thanks to you and to everyone involved!

Thanks, good suggestions!

Now, if there was a way to get rid of this getter and setter overloads, it would start looking less like a hack and more like a real behavior :)

Hi guillemc and heal!

I’m using the MultilingualBehaviour, and it’s working fine in an example I created. The user gets to choose in wich language wants to display the sections and posts related, and it gets the translation correctly.

But my question is how I change the Models and Controllers of the Posts and Section (in the example) to be able to introduce all the files in the diferent lenguages in the Add and Update Form?

Using the previous MultilingualActiveRecord class, by defining the localizedAttributes, languages, etc. it was correctly displayed all the language fields on the form view…

Can you show us the code in order to achieve that?

Thank you!!

Hi!

Now I get the fields in the forms,I understood that you have to edit the _form.php in orther to include the translate fields…

And the Add/Create works fine for me.

But the Edit/Update returns an error (I cannot even see the form):

Property "Posts.title_es" is not defined. //Posts is my Model and title_es the first field in PostLang

the error trace comes from:

return parent::__get($name);

public function __get($name) {

  try { return parent::__get(&#036;name); }  //this line


  catch (CException &#036;e) {


     if (&#036;this-&gt;hasLangAttribute(&#036;name)) return &#036;this-&gt;getLangAttribute(&#036;name);


     else throw &#036;e;


   }                                                     


}

So… i’m a bit lost in here, because I don’t undestand why is looking for the file in the Posts model, instead of the PostsLang model…

Any help?