rkit/translation-behavior-yii2

Translation Behavior for Yii2

2.0.0 2018-08-07 16:14 UTC

This package is not auto-updated.

Last update: 2022-01-16 18:55:07 UTC


README

Build Status Scrutinizer Code Quality

Requirements

PHP 7

Installation

composer require rkit/translation-behavior-yii2

Configuration

For example, we have a Post model and we want to add translation capability.
Let's do it.

  1. Add a post_translation table and a PostTranslation model for the translation
$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(''),
]);
  1. Add a TranslationBehavior behavior to the Post model
public function behaviors()
{
    return [
        'translationBehavior' => [
            'class' => 'rkit\translation\behavior\TranslationBehavior',
            'relationOne' => 'translation',
            'relationMany' => 'translations',
            'languageAttribute' => 'language',
            'defaultLanguage' => 'en',
            'attributes' => [ // attributes for translation
                'title',
            ],

        ],
    ];
}
  1. Add translation and translations relations (see relationOne and relationMany options in the behavior)
/**
 * @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']);
}

Usage

Load translation

$model = new Post();
$model->loadTranslations([
    'en' => ['title' => 'example'],
    'ru' => ['title' => 'пример'],
]);
$model->save();

Get translation

For current language

$model = Post::find()->with('translation')->where(['id' => $id])->one();

echo $model->title;

All translation

$model = Post::find()->with('translations')->where(['id' => $id])->one();

echo $model->translate('en')->title;
echo $model->translate('ru')->title;

Remove translation

$model = new Post();
$model->loadTranslations([]);
$model->save();

Tests

Coding Standard