PHP code example of rkit / translation-behavior-yii2
1. Go to this page and download the library: Download rkit/translation-behavior-yii2 library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
rkit / translation-behavior-yii2 example snippets
$this->createTable('{{%post_translation}}', [
'id' => $this->primaryKey(),
'post_id' => $this->integer()->notNull()->defaultValue(0),
'language' => $this->string(2)->notNull()->defaultValue(''),
'title' => $this->string()->notNull()->defaultValue(''),
]);
public function behaviors()
{
return [
'translationBehavior' => [
'class' => 'rkit\translation\behavior\TranslationBehavior',
'relationOne' => 'translation',
'relationMany' => 'translations',
'languageAttribute' => 'language',
'defaultLanguage' => 'en',
'attributes' => [ // attributes for translation
'title',
],
],
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTranslation()
{
return $this
->hasOne(PostTranslation::class, ['post_id' => 'id'])
->andWhere(['language' => \Yii::$app->language]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTranslations()
{
return $this->hasMany(PostTranslation::class, ['post_id' => 'id']);
}
$model = new Post();
$model->loadTranslations([
'en' => ['title' => 'example'],
'ru' => ['title' => 'пример'],
]);
$model->save();
$model = Post::find()->with('translation')->where(['id' => $id])->one();
echo $model->title;
$model = Post::find()->with('translations')->where(['id' => $id])->one();
echo $model->translate('en')->title;
echo $model->translate('ru')->title;
$model = new Post();
$model->loadTranslations([]);
$model->save();