Skip to content

ZiyaVakhobov/yii2-translatable

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Translatable

You Have to use PHP 7.1 at least

Widget for Yii2 framework projects. To Json Translate.

composer require ziya/yii2-translate "^0.2.1"

Migrations

Attribute that you want translatable should be json field

  $this->createTable('{{%article}}', [
            'id' => $this->primaryKey(),
            'name' => $this->json(),
            ....
        ]);

Active Records

Your model should use trait Translatable.

use Translatable; 

If you want to make them required by language then use TranslatableValidator rule then provide what language is required

TranslatableValidator::class

You have to use TranslatableBehaviour class and show which attribute should follow translatable
TranslatableBehaviour::class

All code is below with examples
class Article extends ActiveRecord
{
    use Translatable; 


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name'], TranslatableValidator::class, 'languages' => ['uz','ru']],
            [['description'],'safe'],
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TranslatableBehaviour::class,
                'attributes' => ['name'']
            ],
        ];
    }

View File

Your Form will look like this. Give languageList as array.

$languageList = ['eng','ru','fr'];

foreach ($languageList as $lang) {
        echo $form
            ->field($model, "name[{$lang}]")
            ->textInput(['value'=>$model->name->other($lang)])
            ->label($model->getAttributeLabel('name') . "_{$lang}");
}

Forms

If you are using Form instead of ActiveRecord. You need to set type to Model.

By default it is TYPE_ACTIVE_RECORD, so you need to set TYPE_MODEL. See below how it is done

class ArticleForm extends Model
{
    
    public $content;
    public function behaviors()
    {
        return [
            'translatable'=>[
                'class' => TranslatableBehaviour::className(),
                'attributes' => ['content'],
                'type' => TranslatableBehaviour::TYPE_MODEL,
            ],
        ];
    }