PHPackages                             nedarta/yii2-translated-behavior - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Localization &amp; i18n](/categories/localization)
4. /
5. nedarta/yii2-translated-behavior

ActiveYii2-extension[Localization &amp; i18n](/categories/localization)

nedarta/yii2-translated-behavior
================================

This extension allows you to quickly and simple enough to add translations for any ActiveRecord models.

00PHP

Since Feb 10Pushed 4mo agoCompare

[ Source](https://github.com/nedarta/yii2-translated-behavior)[ Packagist](https://packagist.org/packages/nedarta/yii2-translated-behavior)[ RSS](/packages/nedarta-yii2-translated-behavior/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (1)Used By (0)

yii2-translated-behavior
========================

[](#yii2-translated-behavior)

[![Latest Stable Version](https://camo.githubusercontent.com/073c3f974acaa9a027286e839645ab8416262a01af07b9c00dd1e2531150b8d2/68747470733a2f2f706f7365722e707567782e6f72672f6c617634352f796969322d7472616e736c617465642d6265686176696f722f762f737461626c65)](https://packagist.org/packages/lav45/yii2-translated-behavior)[![License](https://camo.githubusercontent.com/ed438e3a6b46de10ca917f8f85ea58372422d9903a797204838636bc21947816/68747470733a2f2f706f7365722e707567782e6f72672f6c617634352f796969322d7472616e736c617465642d6265686176696f722f6c6963656e7365)](https://packagist.org/packages/lav45/yii2-translated-behavior)[![Total Downloads](https://camo.githubusercontent.com/8fb118d4ef516868edcd7a72e1ecc69341745b9d09fb8994adc41f1aa43d958a/68747470733a2f2f706f7365722e707567782e6f72672f6c617634352f796969322d7472616e736c617465642d6265686176696f722f646f776e6c6f616473)](https://packagist.org/packages/lav45/yii2-translated-behavior)[![Build Status](https://camo.githubusercontent.com/9d005ec8626829078d621e9b3061f0d72827635a0cf07e4f2dfbd1248dd1b861/68747470733a2f2f7472617669732d63692e6f72672f6c617634352f796969322d7472616e736c617465642d6265686176696f722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/lav45/yii2-translated-behavior)[![Test Coverage](https://camo.githubusercontent.com/cf3b51386c8e145d04632ff6af5dfadb305707d655be959e13ccbd4631686179/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f4c415634352f796969322d7472616e736c617465642d6265686176696f722f6261646765732f636f7665726167652e737667)](https://codeclimate.com/github/LAV45/yii2-translated-behavior/coverage)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/8ecc04e56656a29fbc6b8c59fb85f9a595b83ffa5be04e3cc5e5ec4273fc3c5d/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6c617634352f796969322d7472616e736c617465642d6265686176696f722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/lav45/yii2-translated-behavior/)[![Code Climate](https://camo.githubusercontent.com/f6fd4d61a33a33c6e89c0b45047cfb0cc4a7fea00a6b674d3e7202e2e1a3789c/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f4c415634352f796969322d7472616e736c617465642d6265686176696f722f6261646765732f6770612e737667)](https://codeclimate.com/github/LAV45/yii2-translated-behavior)

The Translated Behavior is a Yii2 extension for ActiveRecord models, that will help you add the possibility of transferring any entity.

You can see [DEMO](https://yii2-translated-behavior.lav45.com)

Note

This is a fork of the original work by **Alexey Loban ([lav45](https://github.com/lav45))**. This version includes several modernizations and improvements for PHP 8.0+.

Changes and Improvements (nedarta version)
------------------------------------------

[](#changes-and-improvements-nedarta-version)

- **PHP 8.0+ Modernization**: Added strict type hints for properties, parameters, and return types across the codebase.
- **Namespace Rebranding**: Refactored to the `nedarta\translate` namespace.
- **Automatic Language Negotiation**: Integrated a new `LanguageNegotiator` and `Bootstrap` class for automatic, model-driven I18N setup.
- **Improved Lifecycle Management**: Fixed a critical bug where `updated_at` (and other owner timestamp attributes) were not updating when only translation fields were changed.
- **Enhanced Attribute Access**: Added `getOldAttribute()` and `getOldAttributes()` support for translated fields within the `TranslatedTrait`.
- **Modernized Test Suite**: Completely overhauled the test suite for compatibility with PHPUnit 9.5+, including a custom database helper set that replaces the discontinued `dbunit`.

Installation
------------

[](#installation)

The preferred way to install this extension through [composer](http://getcomposer.org/download/).

You can set the console

```
$ composer require "lav45/yii2-translated-behavior:1.4.*"

```

or add

```
"lav45/yii2-translated-behavior": "1.4.*"

```

in `require` section in `composer.json` file.

Settings
--------

[](#settings)

First you have to move all the attributes that are required for translation in a separate table. For example, imagine that we want to save the translation of the title and description of your post being. Your table schema should be brought to the following form:

```
    +--------------+        +--------------+       +-------------------+
    |     post     |        |     post     |       |     post_lang     |
    +--------------+        +--------------+       +-------------------+
    | id           |        | id           |       | post_id           |
    | title        |  --->  | created_at   |   +   | lang_id           |
    | description  |        | updated_at   |       | title             |
    | updated_at   |        +--------------+       | description       |
    | created_at   |                               +-------------------+
    +--------------+

```

After you change the table schema, we now need to determine the ratio of our `ActiveRecord` objects and adding behavior:

### Post

[](#post)

```
use yii\db\ActiveRecord;
use nedarta\translate\TranslatedTrait;
use nedarta\translate\TranslatedBehavior;

/**
 * ...
 * @property string $title
 * @property string $description
 */
class Post extends ActiveRecord
{
    use TranslatedTrait;

    public function rules()
    {
        return [
            // ...

            [['title'], 'required'],
            [['title'], 'string', 'max' => 128],

            [['description'], 'required'],
            [['description'], 'string'],
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TranslatedBehavior::class,
                'translateRelation' => 'postLangs', // Specify the name of the connection that will store transfers
//                'languageAttribute' => 'lang_id' // post_lang field from the table that will store the target language
                'translateAttributes' => [
                    'title',
                    'description',
                ],
                // list of owner attributes to be changed when translation is changed.
                // This is useful to trigger TimestampBehavior on the owner model.
                'updateOwnerAttributes' => ['updated_at'],
            ]
        ];
    }

    public function attributeLabels()
    {
        return [
            // ...
            'title' => 'Title',
            'description' => 'Description',
        ];
    }

    public function getPostLangs()
    {
        return $this->hasMany(PostLang::className(), ['post_id' => 'id']);
    }
}
```

### Language model

[](#language-model)

#### migrate

[](#migrate)

[migrate/m151220\_112320\_lang.php](migrate/m151220_112320_lang.php)

Apply with the console command:

```
~$ yii migrate/up --migrationPath=vendor/lav45/yii2-translated-behavior/migrate

```

#### Lang ActiveRecord model cite completely

[](#lang-activerecord-model-cite-completely)

[\\nedarta\\translate\\models\\Lang](src/models/Lang.php)

Using
-----

[](#using)

### Backend

[](#backend)

backend/config/bootstrap.php

```
Yii::$container->set('nedarta\translate\TranslatedBehavior', [
    'language' => isset($_GET['lang_id']) ? $_GET['lang_id'] : null
]);
```

backend/controllers/PostController.php

```
namespace backend\controllers;

use yii\web\Controller;
use yii\data\ActiveDataProvider;

use common\models\Post;
use common\models\Lang;

class PostController extends Controller
{
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Post::find()
                ->with([
                    'currentTranslate', // loadabing data associated with the current translation
                    'hasTranslate' // need to display the status was translated page
                ]),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'langList' => Lang::getList(),
        ]);
    }
// ...
}
```

backend/view/post/index.php

```
