PHP code example of lav45 / yii2-translated-behavior
1. Go to this page and download the library: Download lav45/yii2-translated-behavior library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
lav45 / yii2-translated-behavior example snippets
use yii\db\ActiveRecord;
use lav45\translate\TranslatedTrait;
use lav45\translate\TranslatedBehavior;
/**
* ...
* @property string $title
* @property string $description
*/
class Post extends ActiveRecord
{
use TranslatedTrait;
public function rules()
{
return [
// ...
[['title'], 's', // 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',
]
]
];
}
public function attributeLabels()
{
return [
// ...
'title' => 'Title',
'description' => 'Description',
];
}
public function getPostLangs()
{
return $this->hasMany(PostLang::className(), ['post_id' => 'id']);
}
}
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(),
]);
}
// ...
}
use lav45\translate\models\Lang;
return [
'components' => [
'urlManager' => [
'class' => 'lav45\translate\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\web\UrlRule', // If there is no need to substitute the language, you can use the base class
'pattern' => '',
'route' => 'post/index',
],
[
'pattern' => '<_lang:' . Lang::PATTERN . '>/<id:\d+>',
'route' => 'post/view',
],
[
'pattern' => '<_lang:' . Lang::PATTERN . '>',
'route' => 'post/index',
]
],
],
],
];
namespace frontend\controllers;
use yii\web\Controller;
use common\models\Post;
use lav45\translate\models\Lang;
class PostController extends Controller
{
public function behaviors()
{
return [
[
// ContentNegotiator will be determined from a URL or browser language settings and install it in
// Yii::$app->language, which uses the class TranslatedBehavior as language translation
'class' => 'yii\filters\ContentNegotiator',
'languages' => Lang::getLocaleList()
],
];
}