Giter VIP home page Giter VIP logo

yii2-translateable-behavior's Introduction

About this fork

This is a fork from the original 2amigos/yii2-translateable-behavior, since the original repository is archived (read only) and doesn't accept any pull requests.

There are no ambitions to continue the development, but I'll do some small updates here and there based on my own needs, so feel free to use it or contribute.

If you want to install this fork, you have to add this code to your composer.json (the class has still the original namespace, so there is no need to refactor):

"repositories": [
    {
        "type": "git",
        "url": "https://github.com/OndrejVasicek/yii2-translateable-behavior.git"
    }
]

Changes (sorted from newer to older)

  • new helper method formFieldOptions() for ActiveField when using tabular inputs
  • new helper method removeLanguageFromUniqueRules() - can modify language model rules to properly show errors in form based only on Gii generated rules
  • new method getIndexedErrors() - array of all validation errors from all models indexed by the language
  • new method getErrors() - one dimensional array of all validation errors from all models
  • new method hasErrors() - checking, if any of the models as a validation error
  • new method getLoadedTranslations() - accessing all loaded language models

TranslateableBehavior for Yii2

This behavior has been inspired by the great work of Mikehaertl's Translatable Behavior for Yii 1.*.

It eases the translation of ActiveRecord's attributes as it maps theme from a translation table into the main record. It also automatically loads application language by default.

Sample of use:

<?php

// create a record
$tour = new Tour;

$tour->title = "English title";

// save both the new Tour and a related translation record with the title
$tour->save();


// change language
$tour->language = 'fr';

$tour->title = "French title";

// save translation only
$tour->saveTranslation();

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require "2amigos/yii2-translateable-behavior"

or add

"2amigos/yii2-translateable-behavior" : "~1.1"

to the require section of your application's composer.json file.

Usage

Preparation

First you need to move all the attributes that require to be translated into a separated table. For example, imagine we wish to keep translations of title and description from our tour entity. Our schema should result on the following:

    +--------------+        +--------------+        +-------------------+
    |     tour     |        |     tour     |        |      tour_lang    |
    +--------------+        +--------------+        +-------------------+
    |           id |        |           id |        |                id |
    |        title |  --->  |   created_at |   +    |           tour_id |
    |  description |        |   updated_at |        |          language |
    |   created_at |        +--------------+        |             title |
    |   updated_at |                                |       description |
    +--------------+                                +-------------------+

After we have modified our schema, now we need to define a relation in our ActiveRecord object. The following example assumes that we have already created a TourLang model (see the schema above):

/**
* @return \yii\db\ActiveQuery
*/
public function getTranslations()
{
    return $this->hasMany(TourLang::className(), ['tour_id' => 'id']);
}

Finally, we need to attach our behavior.

use dosamigos\translateable\TranslateableBehavior;

\\ ...

public function behaviors()
{
    return [
        'trans' => [ // name it the way you want
            'class' => TranslateableBehavior::className(),
            // in case you named your relation differently, you can setup its relation name attribute
            // 'relation' => 'translations',
            // in case you named the language column differently on your translation schema
            // 'languageField' => 'language',
            'translationAttributes' => [
                'title', 'description'
            ]
        ],
    ];
}

Basic Usage

// create a record
$tour = new Tour;
$tour->title = "English title";

// save both the new Tour and a related translation record with the title
$tour->save();


// change language
$tour->language = 'fr';

$tour->title = "French title";

// save fr translation only
$tour->saveTranslation();

You may also set multiple translations directly:

$tour = new Tour;
$tour->title = [
  'translations' => [
     'en' => "English title",
     'de' => "Deutscher Titel",
  ],
];

// save both the new Tour and a related translation record with the title
$tour->save();

Fallback language

In case no translation is available for a specific language the behavior allows to specify a fallback translation to load instead. By default the fallback will use the application source language. It can be configured by setting the fallbackLanguage property of the behavior.

Fallback language can be configured to be a single language or per language:

// use english as fallback for all languages when no translation is available
'fallbackLanguage' => 'en',
// alternatively:
'fallbackLanguage' => [
    'de' => 'en', // fall back to English if German translation is missing
    'uk' => 'ru', // fall back to Russian if no Ukrainian translation is available
],

Additionally to the configurable fallback a fallback to non-localized language is applied automatically. E.g. if no translation exists for de-AT (German in Austria) the translation will fall back to de. The fallback goes further if de is not found using the fallbackLanguage configuration, so from the example above it will then try en.

When the fallback is defined in array format and no fallback can be found for a language, the first fallback is returned.

You may disable the fallback mechanism by setting fallbackLanguage to false.

If you want to configure fallback languages globally, you can do so by configuring the TranslateableBehavior class in Yii DI container:

Yii::$container->set('dosamigos\translateable\TranslateableBehavior', ['fallbackLanguage' => 'de']);

Deleting translations

By default, when an active record is deleted, translation records are deleted in the afterSave event. However some database scenarios require different configuration, in case foreign keys restrict the deletion of records.

You may configure 'deleteEvent' to be either ActiveRecord::EVENT_BEFORE_DELETE or ActiveRecord::EVENT_AFTER_DELETE to control on which event the deletion of records should be performed. You may set 'deleteEvent' to false to disable deletion and rely on DB foreign key cascade or implement your own method.

When using the Translateablebehavior in an ActiveRecord you should enable transactions() for the delete operation.

2amigOS!
Web development has never been so fun!
www.2amigos.us

yii2-translateable-behavior's People

Contributors

tonydspaniard avatar cebe avatar ondrejvasicek avatar schmunk42 avatar vintik100 avatar hector-del-rio avatar handcode avatar mrstroz avatar amigo-tabin avatar kurpievski avatar sohelahmed7 avatar gatis-ozols avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.