bessonov87/yii2-mongodb-multilingual-behavior

yii2-multilingual-behavior for mongodb

dev-master 2016-03-10 10:33 UTC

This package is not auto-updated.

Last update: 2025-01-10 20:02:32 UTC


README

Yii2 MongoDb port of the yii2-multilingual-behavior.

Packagist Version Total Downloads Build Status Code Quality Code Coverage

This behavior allows you to create multilingual models and almost use them as normal models. Translations are stored in a separate table in the database (ex: PostLang or NewsLang) for each model, so you can add or remove a language easily, without modifying your database.

Example

If you use multilingual() in a find() query, every model translation is loaded as virtual attributes (title_en, title_fr, title_de, ...).

$model = Post::find()->multilingual()->one();
echo $model->title_en; //echo "English title"
echo $model->title_fr; //echo "Titre en Français"

Installation

Preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist bessonov87/yii2-mongodb-multilingual-behavior

or add

"bessonov87/yii2-mongodb-multilingual-behavior": "*"

to the require section of your composer.json file.

Behavior attributes

Attributes marked as bold are required

Usage

Here an example of base 'news' table:

Attaching this behavior to the model (News in the example). Commented fields have default values.

public function behaviors()
{
    return [
        'ml' => [
            'class' => MultilingualBehavior::className(),
            'languages' => [
                'en-US' => 'English',
		'de' => 'German',
            ],
            //'languageField' => 'language',
            //'localizedPrefix' => '',
            //'requireTranslations' => false',
            //'dynamicLangClass' => true',
            //'langClassName' => PostLang::className(), // or namespace/for/a/class/PostLang
            'defaultLanguage' => 'en',
            'langForeignKey' => 'post_id',
            'tableName' => "newsLang",
            'attributes' => [
                'title', 'text',
            ]
        ],
    ];
}

Then you have to overwrite the find() method in your model

    public static function find()
    {
        return new MultilingualQuery(get_called_class());
    }

As this behavior has MultilingualTrait, you can use it in your query classes

namespace app\models;

use yii\mongodb\ActiveQuery;

class MultilingualQuery extends ActiveQuery
{
    use MultilingualTrait;
}

Form example:

//title will be saved to model table and as translation for default language
$form->field($model, 'title')->textInput(['maxlength' => 255]);
$form->field($model, 'title_en')->textInput(['maxlength' => 255]);