Browse Source

Settings languages

master
Egorka 6 years ago
parent
commit
3a3e813cbe
  1. 18
      backend/bootstrap/SetUp.php
  2. 28
      backend/controllers/settings/ListController.php
  3. 11
      backend/forms/SettingsSearch.php
  4. 2
      backend/messages/ru/main.php
  5. 15
      backend/views/layouts/header.php
  6. 38
      backend/views/settings/list/_form.php
  7. 16
      backend/views/settings/list/_form_tab.php
  8. 26
      backend/views/settings/list/_view_tab.php
  9. 35
      backend/views/settings/list/index.php
  10. 9
      backend/views/settings/list/update.php
  11. 34
      backend/views/settings/list/view.php
  12. 16
      common/modules/pages/forms/PageForm.php
  13. 17
      common/modules/pages/views/manage/page/_form.php
  14. 18
      common/modules/pages/views/manage/page/view.php
  15. 50
      console/migrations/m180910_182109_create_settings_lng_table.php
  16. 54
      core/behaviors/LanguageBehavior.php
  17. 24
      core/entities/Settings.php
  18. 43
      core/forms/SettingsForm.php
  19. 4
      core/repositories/SettingsRepository.php
  20. 12
      core/services/SettingsService.php

18
backend/bootstrap/SetUp.php

@ -44,8 +44,22 @@ class SetUp implements BootstrapInterface
]); ]);
// load settings // load settings
$settings = ArrayHelper::map(Settings::find()->andWhere(['active' => 1])->all(), 'key', 'value', 'section'); $settings = Settings::find()->with('translations')->andWhere(['active' => 1])->all();
$app->params['settings'] = $settings; //$settings = Settings::find()->andWhere(['active' => 1])->all();
//$settings_array = [];
/*foreach ($settings as $setting) {
if (!isset($settings_array[$setting->section])) {
$settings_array[$setting->section] = [];
}
//$settings_array[$setting->section][$setting->key] = $setting->translation->value;
}*/
$settings_array = $settings ? ArrayHelper::map($settings, 'key', function ($el) {
return $el->translation->value;
}, 'section') : [];
//$settings = ArrayHelper::map(Settings::find()->andWhere(['active' => 1])->all(), 'key', 'value', 'section');
$app->params['settings'] = $settings_array;
// Connect backend modules // Connect backend modules

28
backend/controllers/settings/ListController.php

@ -64,9 +64,10 @@ class ListController extends Controller
]; ];
} }
public function actionIndex() public function actionIndex($section = 'site')
{ {
$searchModel = new SettingsSearch(); $searchModel = new SettingsSearch();
$searchModel->section = $section;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams); $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render( return $this->render(
@ -74,16 +75,17 @@ class ListController extends Controller
[ [
'searchModel' => $searchModel, 'searchModel' => $searchModel,
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
'section' => $section,
] ]
); );
} }
public function actionView($id) public function actionView($section, $key)
{ {
return $this->render( return $this->render(
'view', 'view',
[ [
'model' => $this->findModel($id), 'model' => $this->findModel($section, $key),
] ]
); );
} }
@ -95,7 +97,7 @@ class ListController extends Controller
try { try {
$settings = $this->_service->create($form); $settings = $this->_service->create($form);
return $this->redirect(['view', 'id' => $settings->id]); return $this->redirect(['view', 'section' => $settings->section, 'key' => $settings->key]);
} catch (\DomainException $e) { } catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e); Yii::$app->errorHandler->logException($e);
Yii::$app->session->setFlash('error', $e->getMessage()); Yii::$app->session->setFlash('error', $e->getMessage());
@ -112,16 +114,16 @@ class ListController extends Controller
); );
} }
public function actionUpdate($id) public function actionUpdate($section, $key)
{ {
$settings = $this->findModel($id); $settings = $this->findModel($section, $key);
$form = new SettingsForm($settings); $form = new SettingsForm($settings);
if ($form->load(Yii::$app->request->post()) && $form->validate()) { if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try { try {
$this->_service->edit($settings->id, $form); $this->_service->edit($settings->section, $settings->key, $form);
return $this->redirect(['view', 'id' => $settings->id]); return $this->redirect(['view', 'section' => $settings->section, 'key' => $settings->key]);
} catch (\DomainException $e) { } catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e); Yii::$app->errorHandler->logException($e);
Yii::$app->session->setFlash('error', $e->getMessage()); Yii::$app->session->setFlash('error', $e->getMessage());
@ -137,19 +139,19 @@ class ListController extends Controller
); );
} }
public function actionDelete($id) public function actionDelete($section, $key)
{ {
$this->_service->remove($id); $this->_service->remove($section, $key);
return $this->redirect(['index']); return $this->redirect(['index']);
} }
protected function findModel($id) protected function findModel($section, $key)
{ {
if (($model = Settings::findOne($id)) !== null) { if (($model = Settings::find()->andWhere(['section' => $section])->andWhere(['key' => $key])->one()) !== null) {
return $model; return $model;
} else { } else {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested setting does not exist.');
} }
} }
} }

11
backend/forms/SettingsSearch.php

@ -6,7 +6,6 @@
namespace backend\forms; namespace backend\forms;
use core\entities\Settings; use core\entities\Settings;
use yii\base\Model; use yii\base\Model;
use yii\data\ActiveDataProvider; use yii\data\ActiveDataProvider;
@ -28,6 +27,7 @@ class SettingsSearch extends Settings
[['type', 'section', 'key', 'value'], 'safe'], [['type', 'section', 'key', 'value'], 'safe'],
]; ];
} }
/** /**
* @return array * @return array
*/ */
@ -36,8 +36,10 @@ class SettingsSearch extends Settings
// bypass scenarios() implementation in the parent class // bypass scenarios() implementation in the parent class
return Model::scenarios(); return Model::scenarios();
} }
/** /**
* @param $params * @param $params
*
* @return ActiveDataProvider * @return ActiveDataProvider
*/ */
public function search($params) public function search($params)
@ -49,6 +51,11 @@ class SettingsSearch extends Settings
] ]
); );
if (!($this->load($params) && $this->validate())) { if (!($this->load($params) && $this->validate())) {
$query->andFilterWhere(
[
'section' => $this->section,
]
);
return $dataProvider; return $dataProvider;
} }
$query->andFilterWhere( $query->andFilterWhere(
@ -60,7 +67,7 @@ class SettingsSearch extends Settings
); );
$query->andFilterWhere(['like', 'key', $this->key]) $query->andFilterWhere(['like', 'key', $this->key])
->andFilterWhere(['like', 'value', $this->value]); ->andFilterWhere(['like', 'value', $this->value]);
return $dataProvider; return $dataProvider;
} }
} }

2
backend/messages/ru/main.php

@ -39,4 +39,6 @@ return [
'Settings List' => 'Все настройки', 'Settings List' => 'Все настройки',
'Create Setting' => 'Новый параметр', 'Create Setting' => 'Новый параметр',
'Interface Language' => 'Язык интерфейса', 'Interface Language' => 'Язык интерфейса',
'design' => 'Оформление',
'site' => 'Сайт',
]; ];

15
backend/views/layouts/header.php

@ -1,6 +1,6 @@
<?php <?php
use yii\helpers\Html; use yii\helpers\Html;
use core\components\avatar_generator\AvatarGenerator;
/* @var $this \yii\web\View */ /* @var $this \yii\web\View */
/* @var $content string */ /* @var $content string */
@ -197,7 +197,8 @@ use core\components\avatar_generator\AvatarGenerator;
<li class="dropdown messages-menu"> <li class="dropdown messages-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">
<!-- <i class="fa fa-language"></i> --> <!-- <i class="fa fa-language"></i> -->
<span><?= \core\helpers\LanguageHelper::getBackendName(Yii::$app->user->identity->user->backend_language) ?> <i class="caret"></i></span> <span><?= \core\helpers\LanguageHelper::getBackendName(Yii::$app->user->identity->user->backend_language) ?>
<i class="caret"></i></span>
</a> </a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<li class="header"><?= Yii::t('main', 'Interface Language') ?></li> <li class="header"><?= Yii::t('main', 'Interface Language') ?></li>
@ -218,18 +219,22 @@ use core\components\avatar_generator\AvatarGenerator;
<li class="dropdown user user-menu"> <li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="<?= Yii::$app->avatar->show(Yii::$app->user->identity->user->username) ?>" class="user-image" alt="<?= Yii::$app->user->identity->user->username ?>"/> <img src="<?= Yii::$app->avatar->show(Yii::$app->user->identity->user->username) ?>"
class="user-image" alt="<?= Yii::$app->user->identity->user->username ?>"/>
<span class="hidden-xs"><?= Yii::$app->user->identity->user->username ?></span> <span class="hidden-xs"><?= Yii::$app->user->identity->user->username ?></span>
</a> </a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<!-- User image --> <!-- User image -->
<li class="user-header"> <li class="user-header">
<img src="<?= Yii::$app->avatar->show(Yii::$app->user->identity->user->username) ?>" class="img-circle" <img src="<?= Yii::$app->avatar->show(Yii::$app->user->identity->user->username) ?>"
class="img-circle"
alt="<?= Yii::$app->user->identity->user->username ?>"/> alt="<?= Yii::$app->user->identity->user->username ?>"/>
<p> <p>
<?= Yii::$app->user->identity->user->username ?> <?= Yii::$app->user->identity->user->username ?>
<small><?= Yii::t('user', 'Registered: {date}', ['date' => date('d.m.Y', Yii::$app->user->identity->user->created_at)]) ?></small> <small><?= Yii::t('user', 'Registered: {date}', [
'date' => date('d.m.Y', Yii::$app->user->identity->user->created_at)
]) ?></small>
</p> </p>
</li> </li>
<!-- Menu Footer--> <!-- Menu Footer-->

38
backend/views/settings/list/_form.php

@ -9,6 +9,22 @@ use core\forms\SettingsForm;
* @var SettingsForm $model * @var SettingsForm $model
* @var yii\widgets\ActiveForm $form * @var yii\widgets\ActiveForm $form
*/ */
$js2 = '
$(".hint-block").each(function () {
var $hint = $(this);
var label = $hint.parent().find("label");
label.html(label.html() + \' <i style="color:#3c8dbc" class="fa fa-question-circle" aria-hidden="true"></i>\');
label.addClass("help").popover({
html: true,
trigger: "hover",
placement: "bottom",
content: $hint.html()
});
$(this).hide();
});
';
$this->registerJs($js2);
?> ?>
<div class="setting-form"> <div class="setting-form">
@ -22,8 +38,6 @@ use core\forms\SettingsForm;
<?= $form->field($model, 'key')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'key')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'value')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'active')->checkbox(['value' => 1]) ?> <?= $form->field($model, 'active')->checkbox(['value' => 1]) ?>
<?= <?=
@ -31,6 +45,26 @@ use core\forms\SettingsForm;
$model->getTypes() $model->getTypes()
)->hint(Yii::t('main', 'Change at your own risk')) ?> )->hint(Yii::t('main', 'Change at your own risk')) ?>
<?php
$items = [];
foreach (Yii::$app->params['translatedLanguages'] as $language => $language_name) {
$items[] = [
'label' => $language_name,
'content' => $this->render('_form_tab', [
'form' => $form,
'model' => $model,
'language' => $language,
]),
];
}
?>
<div class="nav-tabs-custom">
<?= \yii\bootstrap\Tabs::widget([
'items' => $items
]) ?>
</div>
<div class="form-group"> <div class="form-group">
<?= Html::submitButton(Yii::t('buttons', 'Save'), ['class' => 'btn btn-success']) ?> <?= Html::submitButton(Yii::t('buttons', 'Save'), ['class' => 'btn btn-success']) ?>
</div> </div>

16
backend/views/settings/list/_form_tab.php

@ -0,0 +1,16 @@
<?php
/**
* Created by Error202
* Date: 24.08.2018
*/
/**
* @var $this \yii\web\View
* @var $form \yii\widgets\ActiveForm
* @var $model \core\forms\SettingsForm
* @var $language string
*/
$postfix = $language == Yii::$app->params['defaultLanguage'] ? '' : '_' . $language;
echo $form->field($model, 'value' . $postfix)->textarea(['rows' => 6]);

26
backend/views/settings/list/_view_tab.php

@ -0,0 +1,26 @@
<?php
/**
* Created by Error202
* Date: 25.08.2018
*/
use yii\widgets\DetailView;
use core\entities\Settings;
/**
* @var $this \yii\web\View
* @var $setting Settings
* @var $language string
*/
echo DetailView::widget([
'model' => $setting,
'attributes' => [
[
'label' => Yii::t('main', 'Value'),
'value' => function (Settings $entity) use ($language) {
return $entity->findTranslation($language)->value;
}
],
],
]);

35
backend/views/settings/list/index.php

@ -11,6 +11,7 @@ use backend\components\ToggleColumn;
* @var yii\web\View $this * @var yii\web\View $this
* @var \backend\forms\SettingsSearch $searchModel * @var \backend\forms\SettingsSearch $searchModel
* @var yii\data\ActiveDataProvider $dataProvider * @var yii\data\ActiveDataProvider $dataProvider
* @var string $section
*/ */
$this->title = Yii::t('main', 'Settings'); $this->title = Yii::t('main', 'Settings');
@ -27,6 +28,18 @@ $this->params['breadcrumbs'][] = $this->title;
) ?> ) ?>
</p> </p>
<div class="row">
<div class="col-md-3">
<div class="list-group">
<?php foreach (Settings::find()->select('section')->distinct()->where(['<>', 'section', ''])->all() as $setting) : ?>
<?= Html::a(Yii::t('main', $setting->section), ['/settings/list/index', 'section' => $setting->section], [
'class' => 'list-group-item ' . ($section == $setting->section ? 'active' : ''),
]) ?>
<?php endforeach; ?>
</div>
</div>
<div class="col-md-9">
<div class="box"> <div class="box">
<div class="box-body"> <div class="box-body">
@ -37,18 +50,17 @@ $this->params['breadcrumbs'][] = $this->title;
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
'filterModel' => $searchModel, 'filterModel' => $searchModel,
'columns' => [ 'columns' => [
//'id',
//'type',
[ [
'attribute' => 'section', 'attribute' => 'key',
'filter' => ArrayHelper::map( 'options' => ['style' => 'width: 25%;'],
Settings::find()->select('section')->distinct()->where(['<>', 'section', ''])->all(), ],
'section', [
'section' 'label' => Yii::t('main', 'Value'),
), 'value' => function (Settings $setting) {
return $setting->translation->value;
},
'format' => 'ntext',
], ],
'key',
'value:ntext',
[ [
'class' => ToggleColumn::class, 'class' => ToggleColumn::class,
'attribute' => 'active', 'attribute' => 'active',
@ -68,3 +80,6 @@ $this->params['breadcrumbs'][] = $this->title;
</div> </div>
</div> </div>
</div> </div>
</div>
</div>

9
backend/views/settings/list/update.php

@ -9,11 +9,12 @@ use core\entities\Settings;
* @var Settings $settings * @var Settings $settings
*/ */
$this->title = Yii::t( $this->title = Yii::t('main', 'Updating Setting') . ' ' . $model->section . '.' . $model->key;
'main',
'Updating Setting') . ' ' . $model->section. '.' . $model->key;
$this->params['breadcrumbs'][] = ['label' => Yii::t('main', 'Settings'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => Yii::t('main', 'Settings'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->section. '.' . $model->key, 'url' => ['view', 'id' => $settings->id]]; $this->params['breadcrumbs'][] = [
'label' => $model->section . '.' . $model->key,
'url' => ['view', 'section' => $settings->section, 'key' => $settings->key]
];
$this->params['breadcrumbs'][] = Yii::t('main', 'Editing'); $this->params['breadcrumbs'][] = Yii::t('main', 'Editing');
?> ?>
<div class="setting-update"> <div class="setting-update">

34
backend/views/settings/list/view.php

@ -11,16 +11,23 @@ use yii\widgets\DetailView;
$this->title = $model->section . '.' . $model->key; $this->title = $model->section . '.' . $model->key;
$this->params['breadcrumbs'][] = ['label' => Yii::t('main', 'Settings'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => Yii::t('main', 'Settings'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title; $this->params['breadcrumbs'][] = $this->title;
$css = <<<CSS
.detail-view th {
width: 25%;
}
CSS;
$this->registerCss($css);
?> ?>
<div class="setting-view"> <div class="setting-view">
<p> <p>
<?= Html::a(Yii::t('buttons','All Settings'), ['index'], ['class' => 'btn btn-default']) ?> <?= Html::a(Yii::t('buttons', 'All Settings'), ['index', 'section' => $model->section], ['class' => 'btn btn-default']) ?>
<?= Html::a(Yii::t('buttons', 'Edit'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?> <?= Html::a(Yii::t('buttons', 'Edit'), ['update', 'section' => $model->section, 'key' => $model->key], ['class' => 'btn btn-primary']) ?>
<?= <?=
Html::a( Html::a(
Yii::t('buttons', 'Delete'), Yii::t('buttons', 'Delete'),
['delete', 'id' => $model->id], ['delete', 'section' => $model->section, 'key' => $model->key],
[ [
'class' => 'btn btn-danger', 'class' => 'btn btn-danger',
'data' => [ 'data' => [
@ -38,12 +45,10 @@ $this->params['breadcrumbs'][] = $this->title;
[ [
'model' => $model, 'model' => $model,
'attributes' => [ 'attributes' => [
'id',
'type', 'type',
'section', 'section',
'active:boolean', 'active:boolean',
'key', 'key',
'value:ntext',
[ [
'attribute' => 'created_at', 'attribute' => 'created_at',
'format' => ['datetime', 'php:d.m.Y H:i'], 'format' => ['datetime', 'php:d.m.Y H:i'],
@ -55,6 +60,25 @@ $this->params['breadcrumbs'][] = $this->title;
], ],
] ]
) ?> ) ?>
<?php
$items = [];
foreach (Yii::$app->params['translatedLanguages'] as $language => $language_name) {
$items[] = [
'label' => $language_name,
'content' => $this->render('_view_tab', [
'setting' => $model,
'language' => $language,
]),
];
}
?>
<div class="nav-tabs-custom">
<?= \yii\bootstrap\Tabs::widget([
'items' => $items,
]) ?>
</div>
</div> </div>
</div> </div>
</div> </div>

16
common/modules/pages/forms/PageForm.php

@ -44,7 +44,11 @@ class PageForm extends LanguageDynamicModel
[['title', 'slug', 'meta_title', 'meta_keywords'], 'string', 'max' => 255], [['title', 'slug', 'meta_title', 'meta_keywords'], 'string', 'max' => 255],
[['content', 'meta_description'], 'string'], [['content', 'meta_description'], 'string'],
['slug', SlugValidator::class], ['slug', SlugValidator::class],
[['slug'], 'unique', 'targetClass' => Page::class, 'filter' => function (ActiveQuery $query) { [
['slug'],
'unique',
'targetClass' => Page::class,
'filter' => function (ActiveQuery $query) {
if ($this->type != Page::TYPE_PUBLIC) { if ($this->type != Page::TYPE_PUBLIC) {
$query->andWhere($this->type . '=' . Page::TYPE_PUBLIC); $query->andWhere($this->type . '=' . Page::TYPE_PUBLIC);
} }
@ -53,13 +57,16 @@ class PageForm extends LanguageDynamicModel
if ($this->_page) { if ($this->_page) {
$query->andWhere(['<>', 'id', $this->_page->id]); $query->andWhere(['<>', 'id', $this->_page->id]);
} }
return $query; return $query;
}], }
],
] ]
); );
} }
public function attributeLabels() { public function attributeLabels()
{
return array_merge( return array_merge(
parent::attributeLabels(), parent::attributeLabels(),
[ [
@ -75,7 +82,8 @@ class PageForm extends LanguageDynamicModel
); );
} }
public function attributeHints() { public function attributeHints()
{
return array_merge( return array_merge(
parent::attributeHints(), parent::attributeHints(),
[ [

17
common/modules/pages/views/manage/page/_form.php

@ -1,6 +1,5 @@
<?php <?php
use zertex\ckeditor\CKEditor;
use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
@ -60,17 +59,6 @@ $this->registerJs($js2);
]) ?> ]) ?>
</div> </div>
<!--
<div class="box box-default">
<div class="box-header with-border"><?= Yii::t('pages', 'SEO') ?></div>
<div class="box-body">
< ?= $form->field($model->meta, 'title')->textInput() ?>
< ?= $form->field($model->meta, 'description')->textarea(['rows' => 2]) ?>
< ?= $form->field($model->meta, 'keywords')->textInput() ?>
</div>
</div>
-->
<div class="form-group"> <div class="form-group">
<?= Html::submitButton(Yii::t('buttons', 'Save'), ['class' => 'btn btn-success']) ?> <?= Html::submitButton(Yii::t('buttons', 'Save'), ['class' => 'btn btn-success']) ?>
</div> </div>
@ -95,7 +83,10 @@ $this->registerJs($js2);
'class' => 'btn btn-block btn-flat bg-white', 'class' => 'btn btn-block btn-flat bg-white',
'value' => 'preview', 'value' => 'preview',
'name' => 'submit_preview', 'name' => 'submit_preview',
'formaction' => \yii\helpers\Url::to(['/pages/manage/page/create-preview', 'language' => $language == Yii::$app->params['defaultLanguage'] ? '' : $language]), 'formaction' => \yii\helpers\Url::to([
'/pages/manage/page/create-preview',
'language' => $language == Yii::$app->params['defaultLanguage'] ? '' : $language
]),
'formtarget' => '_blank', 'formtarget' => '_blank',
'style' => 'border:0; background-color:#ffffff;', 'style' => 'border:0; background-color:#ffffff;',
]) ?> ]) ?>

18
common/modules/pages/views/manage/page/view.php

@ -82,17 +82,23 @@ $this->registerCss($css);
<?= date('d.m.Y H:i', $item->revision_at) ?> <?= date('d.m.Y H:i', $item->revision_at) ?>
<?= Html::a(Yii::t('blog', 'View'), \yii\helpers\Url::to(Yii::$app->get('frontendUrlManager')->createAbsoluteUrl(['/pages/page/preview', 'id' => $item->id])), [ <?= Html::a(Yii::t('blog', 'View'),
\yii\helpers\Url::to(Yii::$app->get('frontendUrlManager')->createAbsoluteUrl([
'/pages/page/preview',
'id' => $item->id
])), [
'style' => 'font-size:11px;', 'style' => 'font-size:11px;',
'target' => '_blank', 'target' => '_blank',
]) ?> ]) ?>
| |
<?= Html::a(Yii::t('pages', 'Restore'), ['/pages/manage/page/restore-history', 'id' => $item->id], [ <?= Html::a(Yii::t('pages', 'Restore'),
['/pages/manage/page/restore-history', 'id' => $item->id], [
'style' => 'font-size:11px; color: red', 'style' => 'font-size:11px; color: red',
'data' => [ 'data' => [
'confirm' => Yii::t('pages', 'Are you sure you want to restore this history item?'), 'confirm' => Yii::t('pages',
'Are you sure you want to restore this history item?'),
'method' => 'post', 'method' => 'post',
], ],
]) ?> ]) ?>
@ -104,7 +110,8 @@ $this->registerCss($css);
<?php endforeach; ?> <?php endforeach; ?>
</ul> </ul>
<?= Html::a(Yii::t('pages', 'Clear History'), ['/pages/manage/page/clear-history', 'id' => $page->id], [ <?= Html::a(Yii::t('pages', 'Clear History'),
['/pages/manage/page/clear-history', 'id' => $page->id], [
'class' => 'btn btn-danger btn-sm pull-right', 'class' => 'btn btn-danger btn-sm pull-right',
'data' => [ 'data' => [
'confirm' => Yii::t('pages', 'Are you sure you want to remove this history?'), 'confirm' => Yii::t('pages', 'Are you sure you want to remove this history?'),
@ -112,7 +119,8 @@ $this->registerCss($css);
], ],
]) ?> ]) ?>
<?php else: ?> <?php else: ?>
<div style="padding: 20px 0; text-align: center"><?= Yii::t('pages', 'History is empty') ?></div> <div style="padding: 20px 0; text-align: center"><?= Yii::t('pages',
'History is empty') ?></div>
<?php endif; ?> <?php endif; ?>
</div> </div>

50
console/migrations/m180910_182109_create_settings_lng_table.php

@ -0,0 +1,50 @@
<?php
use yii\db\Migration;
/**
* Handles the creation of table `settings_lng`.
*/
class m180910_182109_create_settings_lng_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('{{%settings_lng}}', [
'id' => $this->primaryKey(),
'language' => $this->string(6)->notNull(),
'section' => $this->string(255)->notNull(),
'key' => $this->string(255)->notNull(),
'value' => $this->text(),
], $tableOptions);
$this->createIndex('key', '{{%settings_lng}}', ['section', 'key']);
$this->createIndex('idx_settings_lng_language', '{{%settings_lng}}', 'language');
$this->addForeignKey('frg_settings_lng_settings_setting_id_id', '{{%settings_lng}}', ['section', 'key'], '{{%settings}}', ['section', 'key'], 'CASCADE', 'CASCADE');
$this->dropColumn('{{%settings}}', 'id');
$this->addPrimaryKey('key', '{{%settings}}', ['section', 'key']);
$this->dropColumn('{{%settings}}', 'value');
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->addColumn('{{%settings}}', 'value', $this->text());
$this->dropPrimaryKey('key', '{{%settings}}');
$this->addColumn('{{%settings}}', 'id', $this->primaryKey());
$this->dropForeignKey('frg_settings_lng_settings_setting_id_id', '{{%settings_lng}}');
$this->dropIndex('idx_settings_lng_language', '{{%settings_lng}}');
$this->dropTable('{{%settings_lng}}');
}
}

54
core/behaviors/LanguageBehavior.php

@ -33,7 +33,7 @@ class LanguageBehavior extends Behavior
/** /**
* Field name for tables relative, ex.: 'post_id' * Field name for tables relative, ex.: 'post_id'
* @var string * @var array|string
*/ */
public $relativeField; public $relativeField;
@ -91,7 +91,8 @@ class LanguageBehavior extends Behavior
/** @var ActiveRecord $owner */ /** @var ActiveRecord $owner */
parent::attach($owner); parent::attach($owner);
if (empty($this->translatedLanguages) || !is_array($this->translatedLanguages)) { if (empty($this->translatedLanguages) || !is_array($this->translatedLanguages)) {
throw new InvalidConfigException('Please specify array of available languages for the ' . get_class($this) . ' in the ' . get_class($this->owner) . ' or in the application parameters', 101); throw new InvalidConfigException('Please specify array of available languages for the ' . get_class($this) . ' in the ' . get_class($this->owner) . ' or in the application parameters',
101);
} }
if (array_values($this->translatedLanguages) !== $this->translatedLanguages) { //associative array if (array_values($this->translatedLanguages) !== $this->translatedLanguages) { //associative array
@ -265,7 +266,14 @@ class LanguageBehavior extends Behavior
/** @var ActiveRecord $translation */ /** @var ActiveRecord $translation */
$translation = new $this->virtualClassName; $translation = new $this->virtualClassName;
$translation->{$this->languageField} = $language; $translation->{$this->languageField} = $language;
if (is_array($this->relativeField)) {
foreach ($this->relativeField as $field) {
$translation->{$field} = $owner->{$field};
}
} else {
$translation->{$this->relativeField} = $owner->getPrimaryKey(); $translation->{$this->relativeField} = $owner->getPrimaryKey();
}
} else { } else {
$translation = $translations[$language]; $translation = $translations[$language];
} }
@ -315,8 +323,17 @@ class LanguageBehavior extends Behavior
public function getTranslations() public function getTranslations()
{ {
/** @var ActiveRecord */ /** @var ActiveRecord */
$condition = [];
if (is_array($this->relativeField)) {
foreach ($this->relativeField as $field) {
//$condition[$field] = $this->owner->{$field};
$condition[$field] = $field;
}
return $this->owner->hasMany($this->virtualClassName, $condition);
} else {
return $this->owner->hasMany($this->virtualClassName, [$this->relativeField => $this->_ownerPrimaryKey]); return $this->owner->hasMany($this->virtualClassName, [$this->relativeField => $this->_ownerPrimaryKey]);
} }
}
public function getTranslation($language = null) public function getTranslation($language = null)
{ {
@ -327,27 +344,58 @@ class LanguageBehavior extends Behavior
$language = $language ?: \Yii::$app->language; $language = $language ?: \Yii::$app->language;
//} //}
// if translate exists // if translate exists
if (is_array($this->relativeField)) {
$condition = [];
foreach ($this->relativeField as $field) {
$condition[$field] = $this->owner->{$field};
}
$translate = $this->virtualClassName::find()
->andWhere($condition)
->andWhere([$this->languageField => $language])
->one();
} else {
$translate = $this->virtualClassName::find() $translate = $this->virtualClassName::find()
->andWhere([$this->relativeField => $this->owner->id]) ->andWhere([$this->relativeField => $this->owner->id])
->andWhere([$this->languageField => $language]) ->andWhere([$this->languageField => $language])
->one(); ->one();
}
$language = $translate ? $language : $this->defaultLanguage; $language = $translate ? $language : $this->defaultLanguage;
if (is_array($this->relativeField)) {
$condition = [];
foreach ($this->relativeField as $field) {
$condition[$field] = $field;
}
return $this->owner->hasOne($this->virtualClassName, $condition)
->where([$this->languageField => $language]);
} else {
return $this->owner->hasOne($this->virtualClassName, [$this->relativeField => $this->_ownerPrimaryKey]) return $this->owner->hasOne($this->virtualClassName, [$this->relativeField => $this->_ownerPrimaryKey])
->where([$this->languageField => $language]); ->where([$this->languageField => $language]);
} }
}
public function findTranslation($language = null) public function findTranslation($language = null)
{ {
$language = $language ?: $this->defaultLanguage; $language = $language ?: $this->defaultLanguage;
//$class = call_user_func(array($this->virtualClassName, 'getInstance')); //$class = call_user_func(array($this->virtualClassName, 'getInstance'));
if (is_array($this->relativeField)) {
$condition = [];
foreach ($this->relativeField as $field) {
$condition[$field] = $this->owner{$field};
}
return $this->virtualClassName::find()
->andWhere($condition)
->andWhere([$this->languageField => $language])
->one();
} else {
return $this->virtualClassName::find() return $this->virtualClassName::find()
->andWhere([$this->relativeField => $this->owner->id]) ->andWhere([$this->relativeField => $this->owner->id])
->andWhere([$this->languageField => $language]) ->andWhere([$this->languageField => $language])
->one(); ->one();
} }
}
public function hasLangAttribute($name) public function hasLangAttribute($name)
{ {

24
core/entities/Settings.php

@ -9,9 +9,9 @@ namespace core\entities;
use Yii; use Yii;
use yii\db\ActiveRecord; use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior; use yii\behaviors\TimestampBehavior;
use core\behaviors\LanguageBehavior;
/** /**
* @property integer $id
* @property string $type * @property string $type
* @property string $section * @property string $section
* @property string $key * @property string $key
@ -23,6 +23,8 @@ use yii\behaviors\TimestampBehavior;
class Settings extends ActiveRecord class Settings extends ActiveRecord
{ {
public $_form;
public static function tableName(): string public static function tableName(): string
{ {
return '{{%settings}}'; return '{{%settings}}';
@ -31,7 +33,6 @@ class Settings extends ActiveRecord
public function attributeLabels() public function attributeLabels()
{ {
return [ return [
'id' => Yii::t('main', 'ID'),
'type' => Yii::t('main', 'Type'), 'type' => Yii::t('main', 'Type'),
'section' => Yii::t('main', 'Section'), 'section' => Yii::t('main', 'Section'),
'key' => Yii::t('main', 'Key'), 'key' => Yii::t('main', 'Key'),
@ -42,31 +43,42 @@ class Settings extends ActiveRecord
]; ];
} }
public static function create($type, $section, $key, $value, $active): self public static function create($form, $type, $section, $key, $active): self
{ {
$settings = new static(); $settings = new static();
$settings->type = $type; $settings->type = $type;
$settings->section = $section; $settings->section = $section;
$settings->key = $key; $settings->key = $key;
$settings->value = $value;
$settings->active = $active; $settings->active = $active;
$settings->_form = $form;
return $settings; return $settings;
} }
public function edit($type, $section, $key, $value, $active): void public function edit($form, $type, $section, $key, $active): void
{ {
$this->type = $type; $this->type = $type;
$this->section = $section; $this->section = $section;
$this->key = $key; $this->key = $key;
$this->value = $value;
$this->active = $active; $this->active = $active;
$this->_form = $form;
} }
public function behaviors(): array public function behaviors(): array
{ {
return [ return [
TimestampBehavior::class, TimestampBehavior::class,
[
'class' => LanguageBehavior::class,
'virtualClassName' => 'SettingsVirtualTranslate',
'translatedLanguages' => \Yii::$app->params['translatedLanguages'],
'relativeField' => ['section', 'key'],
'tableName' => '{{%settings_lng}}',
'attributes' => ['value'],
'defaultLanguage' => \Yii::$app->params['defaultLanguage'],
],
]; ];
} }
} }

43
core/forms/SettingsForm.php

@ -6,24 +6,24 @@
namespace core\forms; namespace core\forms;
use core\components\LanguageDynamicModel;
use core\entities\Settings; use core\entities\Settings;
use yii\base\DynamicModel; use yii\base\DynamicModel;
use yii\base\Model;
use yii\helpers\Json; use yii\helpers\Json;
use yii\base\InvalidParamException;
use Yii; use Yii;
class SettingsForm extends Model class SettingsForm extends LanguageDynamicModel
{ {
public $type; public $type;
public $section; public $section;
public $key; public $key;
public $value; public $value;
public $active; public $active;
private $_settings;
public function __construct(Settings $settings = null, $config = []) public $_settings;
//public function __construct(Settings $settings = null, $config = [])
public function __construct(Settings $settings = null, array $attributes = [], $config = [])
{ {
if ($settings) { if ($settings) {
$this->type = $settings->type; $this->type = $settings->type;
@ -33,12 +33,15 @@ class SettingsForm extends Model
$this->active = $settings->active; $this->active = $settings->active;
$this->_settings = $settings; $this->_settings = $settings;
} }
parent::__construct($config); //parent::__construct($config);
parent::__construct($settings, $attributes, $config);
} }
public function rules() public function rules()
{ {
return [ return array_merge(
parent::rules(),
[
[['value'], 'string'], [['value'], 'string'],
[['section', 'key'], 'string', 'max' => 255], [['section', 'key'], 'string', 'max' => 255],
[ [
@ -46,14 +49,16 @@ class SettingsForm extends Model
'unique', 'unique',
'targetAttribute' => ['section', 'key'], 'targetAttribute' => ['section', 'key'],
'targetClass' => Settings::class, 'targetClass' => Settings::class,
'filter' => $this->_settings ? ['<>', 'id', $this->_settings->id] : null, //'filter' => $this->_settings ? ['<>', 'id', $this->_settings->id] : null,
'filter' => $this->_settings ? ['AND', ['<>', 'section', $this->_settings->section], ['<>', 'key', $this->_settings->key]] : null,
'message' => 'message' =>
Yii::t('main', '{attribute} "{value}" already exists for this section.') Yii::t('main', '{attribute} "{value}" already exists for this section.')
], ],
['type', 'in', 'range' => array_keys($this->getTypes(false))], ['type', 'in', 'range' => array_keys($this->getTypes(false))],
[['type'], 'safe'], [['type'], 'safe'],
[['active'], 'integer'], [['active'], 'integer'],
]; ]
);
} }
public function getTypes($forDropDown = true) public function getTypes($forDropDown = true)
@ -61,7 +66,7 @@ class SettingsForm extends Model
$values = [ $values = [
'string' => ['value', 'string'], 'string' => ['value', 'string'],
'integer' => ['value', 'integer'], 'integer' => ['value', 'integer'],
'boolean' => ['value', 'boolean', 'trueValue' => "1", 'falseValue' => "0", 'strict' => true], 'boolean' => ['value', 'boolean', 'trueValue' => '1', 'falseValue' => '0', 'strict' => true],
'float' => ['value', 'number'], 'float' => ['value', 'number'],
'email' => ['value', 'email'], 'email' => ['value', 'email'],
'ip' => ['value', 'ip'], 'ip' => ['value', 'ip'],
@ -72,7 +77,7 @@ class SettingsForm extends Model
$object = null; $object = null;
try { try {
Json::decode($this->$attribute); Json::decode($this->$attribute);
} catch (InvalidParamException $e) { } catch (\InvalidArgumentException $e) {
$this->addError($attribute, Yii::t('main', '"{attribute}" must be a valid JSON object', [ $this->addError($attribute, Yii::t('main', '"{attribute}" must be a valid JSON object', [
'attribute' => $attribute, 'attribute' => $attribute,
])); ]));
@ -87,12 +92,15 @@ class SettingsForm extends Model
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
$return[$key] = Yii::t('main', $key); $return[$key] = Yii::t('main', $key);
} }
return $return; return $return;
} }
public function attributeLabels() public function attributeLabels()
{ {
return [ return array_merge(
parent::attributeLabels(),
[
'id' => Yii::t('main', 'ID'), 'id' => Yii::t('main', 'ID'),
'type' => Yii::t('main', 'Type'), 'type' => Yii::t('main', 'Type'),
'section' => Yii::t('main', 'Section'), 'section' => Yii::t('main', 'Section'),
@ -101,13 +109,16 @@ class SettingsForm extends Model
'active' => Yii::t('main', 'Active'), 'active' => Yii::t('main', 'Active'),
'crated_at' => Yii::t('main', 'Created At'), 'crated_at' => Yii::t('main', 'Created At'),
'updated_at' => Yii::t('main', 'Updated At'), 'updated_at' => Yii::t('main', 'Updated At'),
]; ]
);
} }
public function beforeValidate() { public function beforeValidate()
{
$validators = $this->getTypes(false); $validators = $this->getTypes(false);
if (!array_key_exists($this->type, $validators)) { if (!array_key_exists($this->type, $validators)) {
$this->addError('type', Yii::t('main', 'Please select correct type')); $this->addError('type', Yii::t('main', 'Please select correct type'));
return false; return false;
} }
$model = DynamicModel::validateData([ $model = DynamicModel::validateData([
@ -117,11 +128,13 @@ class SettingsForm extends Model
]); ]);
if ($model->hasErrors()) { if ($model->hasErrors()) {
$this->addError('value', $model->getFirstError('value')); $this->addError('value', $model->getFirstError('value'));
return false; return false;
} }
if ($this->hasErrors()) { if ($this->hasErrors()) {
return false; return false;
} }
return parent::beforeValidate(); return parent::beforeValidate();
} }
} }

4
core/repositories/SettingsRepository.php

@ -6,9 +6,9 @@ use core\entities\Settings;
class SettingsRepository class SettingsRepository
{ {
public function get($id): Settings public function get($section, $key): Settings
{ {
if (!$settings = Settings::findOne($id)) { if (!$settings = Settings::find()->andWhere(['section' => $section])->andWhere(['key' => $key])->one()) {
throw new NotFoundException('Setting is not found.'); throw new NotFoundException('Setting is not found.');
} }
return $settings; return $settings;

12
core/services/SettingsService.php

@ -18,10 +18,10 @@ class SettingsService
public function create(SettingsForm $form): Settings public function create(SettingsForm $form): Settings
{ {
$settings = Settings::create( $settings = Settings::create(
$form,
$form->type, $form->type,
$form->section, $form->section,
$form->key, $form->key,
$form->value,
$form->active $form->active
); );
$this->_repository->save($settings); $this->_repository->save($settings);
@ -29,22 +29,22 @@ class SettingsService
return $settings; return $settings;
} }
public function edit($id, SettingsForm $form): void public function edit($section, $key, SettingsForm $form): void
{ {
$settings = $this->_repository->get($id); $settings = $this->_repository->get($section, $key);
$settings->edit( $settings->edit(
$form,
$form->type, $form->type,
$form->section, $form->section,
$form->key, $form->key,
$form->value,
$form->active $form->active
); );
$this->_repository->save($settings); $this->_repository->save($settings);
} }
public function remove($id): void public function remove($section, $key): void
{ {
$settings = $this->_repository->get($id); $settings = $this->_repository->get($section, $key);
$this->_repository->remove($settings); $this->_repository->remove($settings);
} }
} }

Loading…
Cancel
Save