PHPackages                             ciedooy/yii2-translateable - 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. ciedooy/yii2-translateable

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

ciedooy/yii2-translateable
==========================

The translateable behavior for the Yii framework

1.1.4(8y ago)055BSD-3-ClausePHP

Since Feb 26Pushed 8y agoCompare

[ Source](https://github.com/ciedooy/yii2-translateable)[ Packagist](https://packagist.org/packages/ciedooy/yii2-translateable)[ RSS](/packages/ciedooy-yii2-translateable/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (3)Versions (7)Used By (0)

Translateable Behavior for Yii 2
================================

[](#translateable-behavior-for-yii-2)

[![Packagist Version](https://camo.githubusercontent.com/752138c41b0afed1f251fb0f57e61120fdc2aace8395ecd3536805d5c58cf85d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636965646f6f792f796969322d7472616e736c61746561626c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ciedooy/yii2-translateable)

A modern translateable behavior for the Yii framework.

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

[](#installation)

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

Either run

```
$ composer require ciedooy/yii2-translateable
```

or add

```
"ciedooy/yii2-translateable": "~1.0"

```

to the `require` section of your `composer.json` file.

Migrations
----------

[](#migrations)

Run the following command

```
$ yii migrate/create create_post_table
```

Open the `/path/to/migrations/m_xxxxxx_xxxxxx_create_post_table.php` file, inside the `up()` method add the following

```
$this->createTable('{{%post}}', [
    'id' => Schema::TYPE_PK,
]);
```

Run the following command

```
$ yii migrate/create create_post_translation_table
```

Open the `/path/to/migrations/m_xxxxxx_xxxxxx_create_post_translation_table.php` file, inside the `up()` method add the following

```
$this->createTable('{{%post_translation}}', [
    'post_id' => Schema::TYPE_INTEGER . ' NOT NULL',
    'language' => Schema::TYPE_STRING . '(16) NOT NULL',
    'title' => Schema::TYPE_STRING . ' NOT NULL',
    'body' => Schema::TYPE_TEXT . ' NOT NULL',
]);

$this->addPrimaryKey('', '{{%post_translation}}', ['post_id', 'language']);
```

Configuring
-----------

[](#configuring)

Configure model as follows

```
use creocoder\translateable\TranslateableBehavior;

/**
 * ...
 * @property string $title
 * @property string $body
 * ...
 */
class Post extends \yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            'translateable' => [
                'class' => TranslateableBehavior::className(),
                'translationAttributes' => ['title', 'body'],
                // translationRelation => 'translations',
                // translationLanguageAttribute => 'language',
            ],
        ];
    }

    public function transactions()
    {
        return [
            self::SCENARIO_DEFAULT => self::OP_ALL,
        ];
    }

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

Model `PostTranslation` can be generated using Gii.

With the subsequent removal `post_id` from `required` rules

```
   /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[ /* 'post_id', !!! */ 'language'], 'required'],
            [['post_id'], 'integer'],
            [['language'], 'string', 'max' => 15],
            // .....
];
    }
```

Usage
-----

[](#usage)

### Setting translations to the entity

[](#setting-translations-to-the-entity)

To set translations to the entity

```
$post = new Post();

// title attribute translation for default application language
$post->title = 'Post title';

// body attribute translation for default application language
$post->body = 'Post body';

// title attribute translation for German
$post->translate('de-DE')->title = 'Post titel';

// body attribute translation for German
$post->translate('de-DE')->body = 'Post inhalt';

// title attribute translation for Russian
$post->translate('ru-RU')->title = 'Заголовок поста';

// body attribute translation for Russian
$post->translate('ru-RU')->body = 'Тело поста';

// save post and its translations
$post->save();
```

### Getting translations from the entity

[](#getting-translations-from-the-entity)

To get translations from the entity

```
$posts = Post::find()->with('translations')->all();

foreach ($posts as $post) {
    // title attribute translation for default application language
    $title = $post->title;

    // body attribute translation for default application language
    $body = $post->body;

    // title attribute translation for German
    $germanTitle = $post->translate('de-DE')->title;

    // body attribute translation for German
    $germanBody = $post->translate('de-DE')->body;

    // title attribute translation for Russian
    $russianTitle = $post->translate('ru-RU')->title;

    // body attribute translation for Russian
    $russianBody = $post->translate('ru-RU')->body;
}
```

### Checking for translations in the entity

[](#checking-for-translations-in-the-entity)

To check translations in the entity

```
$post = Post::findOne(1);

// checking for default application language translation
$result = $post->hasTranslation();

// checking for German translation
$result = $post->hasTranslation('de-DE');

// checking for Russian translation
$result = $post->hasTranslation('ru-RU');
```

Advanced usage
--------------

[](#advanced-usage)

### Collecting tabular input

[](#collecting-tabular-input)

Example of controller actions

```
class PostController extends Controller
{
    public function actionCreate()
    {
        $model = new Post();

        //...
    }

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

        if ($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        //...
    }
}
```

Example of view form

```
