rkit / translation-behavior-yii2
Translation Behavior for Yii2
Installs: 7
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 3
Forks: 0
Open Issues: 0
Type:yii2-extension
Requires
- yiisoft/yii2: ^2.0.0, !=2.0.15.1
Requires (Dev)
- phpunit/dbunit: ^4.0
- phpunit/phpunit: ^7.2
- squizlabs/php_codesniffer: ^3.3
This package is not auto-updated.
Last update: 2024-11-04 08:38:44 UTC
README
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.
- Add a
post_translation
table and aPostTranslation
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(''), ]);
- Add a
TranslationBehavior
behavior to thePost
model
public function behaviors() { return [ 'translationBehavior' => [ 'class' => 'rkit\translation\behavior\TranslationBehavior', 'relationOne' => 'translation', 'relationMany' => 'translations', 'languageAttribute' => 'language', 'defaultLanguage' => 'en', 'attributes' => [ // attributes for translation 'title', ], ], ]; }
- Add
translation
andtranslations
relations (seerelationOne
andrelationMany
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
- PHP Code Sniffer (phpcs.xml)