bessonov87 / yii2-mongodb-multilingual-behavior
yii2-multilingual-behavior for mongodb
Installs: 2
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 0
Forks: 0
Open Issues: 0
Type:yii2-extension
Requires
- yiisoft/yii2: *
- yiisoft/yii2-mongodb: ~2.0
This package is not auto-updated.
Last update: 2025-01-10 20:02:32 UTC
README
Yii2 MongoDb port of the yii2-multilingual-behavior.
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]);