Browse Source

Restructure widgets codes

Forms languages
master
Egorka 6 years ago
parent
commit
f82c9c9913
  1. 1
      backend/components/form_builder/assets/FormBuilderAsset.php
  2. 92
      backend/components/form_builder/js/languages/en.lang
  3. 92
      backend/components/form_builder/js/languages/ru.lang
  4. 55
      backend/views/menu/menu.php
  5. 5
      common/behaviors/WidgetContentBehavior.php
  6. 47
      common/modules/banners/views/manage/place/view.php
  7. 10
      common/modules/forms/FormsModule.php
  8. 59
      common/modules/forms/controllers/manage/FormController.php
  9. 41
      common/modules/forms/urls/FormsUrlRule.php
  10. 8
      common/modules/forms/views/manage/form/_form/_form-builder.php
  11. 49
      common/modules/forms/views/manage/form/view.php
  12. 2
      common/modules/pages/PagesModule.php
  13. 10
      common/modules/pages/controllers/PageController.php
  14. 10
      common/modules/pages/entities/Page.php
  15. 6
      common/modules/pages/urls/PageMainUrlRule.php
  16. 7
      frontend/components/FrontendController.php

1
backend/components/form_builder/assets/FormBuilderAsset.php

@ -6,7 +6,6 @@
namespace backend\components\form_builder\assets;
use yii\jui\JuiAsset;
use yii\web\AssetBundle;

92
backend/components/form_builder/js/languages/en.lang

@ -0,0 +1,92 @@
addOption = Add option
allFieldsRemoved = Allfields deleted
allowSelect = Allow select
autocomplete = Autocomplete
button = Button
cannotBeEmpty = This field cannot be empty
checkboxGroup = Checkbox group
checkbox = Checkbox
checkboxes = Checkboxes
class = Class
clearAllMessage = Are you sure, clear all fields?
clear = Clear
close = Close
content = Content
copy = Copy
dateField = Date field
description = Hint
descriptionField = Description
devMode = Debug mode
editNames = Edit names
editorTitle = Form elements
editXML = Edit XML
fieldDeleteWarning: false
fieldVars = Variable fields
fieldNonEditable = Non editable field
fieldRemoveWarning = Are you sure, delete this field?
fileUpload = Upload
formUpdated = Form updated
getStarted = Drag field from right side here
header = Header
hide = Edit
hidden = Hidden field
label = Label
labelEmpty = Label cannot be empty
limitRole = Deny access for one/some roles:
mandatory = Required
maxlength = Max length
minOptionMessage = Select more then 1 options for this field
name = Name
no = No
off = Off
on = On
option = Option
optional = Optional
optionEmpty = Option must have a value
paragraph = Paragraph
placeholder = Placeholder
placeholder.value = Value
placeholder.label = Label
placeholder.text = Enter anything
placeholder.textarea = Enter a text
placeholder.email = Enter your EMAIL
placeholder.placeholder = Placeholder
placeholder.className = Class names divided by spaces
placeholder.password = Enter you password
preview = Preview
radioGroup = Radio group
radio = Radio
removeMessage = Delete element
remove = ×
required = Required
richText = Text editor
roles = Roles
save = Save
selectOptions = Options
select = Select
selectColor = Select color
selectionsMessage = Multiselection enabled
size = Size
sizes = Sizes
sizes.xs = Very small
sizes.sm = Small
sizes.m = Default
sizes.lg = Big
style = Style
styles = Styles
styles.btn = Button style
styles.btn.default = Default
styles.btn.danger = Danger!
styles.btn.info = Info
styles.btn.primary = Primary
styles.btn.success = Success
styles.btn.warning = Warning
subtype = Type
text = Text field
textArea = Textarea
toggle = Toggle
value = Value
warning = Warning!
viewXML = </>
viewJSON = { }
yes = Yes

92
backend/components/form_builder/js/languages/ru.lang

@ -0,0 +1,92 @@
addOption = Добавить опцию
allFieldsRemoved = Все поля удалены
allowSelect = Позволить выбор
autocomplete = Автозаполнение
button = Кнопка
cannotBeEmpty = Данное поле не может быть пустым
checkboxGroup = Группа Чекбоксов
checkbox = Чекбокс
checkboxes = Чекбоксы
class = Класс
clearAllMessage = Вы уверены, что хотите очистить все поля?
clear = Очистить
close = Закрыть
content = Содержимое
copy = Копировать в буфер
dateField = Поле Дата
description = Подсказка
descriptionField = Описание
devMode = Режим отладки
editNames = Редактировать Имена
editorTitle = Элементы формы
editXML = Редактировать XML
fieldDeleteWarning: ложь
fieldVars = Переменные Поля
fieldNonEditable = Данное поле не является редактируемым
fieldRemoveWarning = Вы уверены, что хотите удалить данное поле?
fileUpload = Загрузка файла
formUpdated = Форма обновлена
getStarted = Перетащите поле из правой области в эту зону
header = Заголовок
hide = Редактировать
hidden = Скрытое поле ввода
label = Метка
labelEmpty = Метка поля не может быть пустой
limitRole = Ограниченный доступ к одной или нескольким из следующих ролей:
mandatory = Обязательно
maxlength = Максимальная длина
minOptionMessage = Данное поле требует указания хотя бы 2-х опций
name = Имя
no = Нет
off = Выкл.
on = Вкл.
option = Опция
optional = Опциональный
optionEmpty = Требуется значение опции
paragraph = Параграф
placeholder = Заглушка
placeholder.value = Значение
placeholder.label = Метка
placeholder.text = Введите что-нибудь
placeholder.textarea = Введите много текста
placeholder.email = Введите Ваш EMAIL
placeholder.placeholder = Заглушка
placeholder.className = Имена классов, разделенные пробелами
placeholder.password = Введите Ваш пароль
preview = Предосмотр
radioGroup = Группа радио-контролов
radio = Радио-контрол
removeMessage = Удалить элемент
remove = ×
required = Требуется
richText = Редактор текста
roles = Доступ
save = Сохранить
selectOptions = Опции
select = Выбрать
selectColor = Выбрать цвет
selectionsMessage = Множественный выбор включен
size = Размер
sizes = Размеры
sizes.xs = Очень маленький
sizes.sm = Маленький
sizes.m = По умолчанию
sizes.lg = Большой
style = Стиль
styles = Стили
styles.btn = Стиль кнопки
styles.btn.default = По умолчанию
styles.btn.danger = Опасно!
styles.btn.info = Информация
styles.btn.primary = Главная
styles.btn.success = Удачный
styles.btn.warning = Предупреждение
subtype = Тип
text = Текстовое поле
textArea = Поле текста
toggle = Переключатель
value = Значение
warning = Внимание!
viewXML = </>
viewJSON = { }
yes = Да

55
backend/views/menu/menu.php

@ -5,7 +5,6 @@
*/
use kartik\form\ActiveForm;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
/**
@ -19,6 +18,26 @@ use yii\helpers\Html;
$this->title = Yii::t('menu', 'Menu');
$this->params['breadcrumbs'][] = Html::encode(isset($menu->translation) ? $menu->translation->name : Yii::t('menu', 'Not set'));
$this->params['breadcrumbs'][] = $this->title;
$js2 = <<<JS2
$("#copyEditorCodeButton").on('click', function(){
CopyToClipboard($('#code_editor'));
});
$("#copyTemplateCodeButton").on('click', function(){
CopyToClipboard($('#code_template'));
});
JS2;
$this->registerJs($js2, $this::POS_READY);
$js = <<<JS
function CopyToClipboard(selector) {
var body = $("body");
selector.select();
document.execCommand("copy");
}
JS;
$this->registerJs($js, $this::POS_HEAD);
?>
<div class="menu">
@ -77,7 +96,8 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="panel panel-default">
<div class="panel-heading" style="padding-left: 0">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse<?= $item['id'] ?>"><?= $item['title'] ?>
<a data-toggle="collapse" data-parent="#accordion"
href="#collapse<?= $item['id'] ?>"><?= $item['title'] ?>
<i class="fa fa-angle-down pull-right" aria-hidden="true"></i></a>
</h4>
</div>
@ -114,22 +134,33 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="box-body">
<?php
$code = Html::encode(
"<?= \core\widgets\menu\MenuWidget::widget([
'menu_id' => ".$menu->id.",
]) ?>");
$code = "<?= \core\widgets\menu\MenuWidget::widget(['menu_id' => " . $menu->id . ']) ?>';
?>
<p><?= Yii::t('menu', 'For template') ?></p>
<pre><?= $code ?></pre>
<div class="input-group">
<?= Html::input('text', 'code_template', $code, [
'class' => 'form-control',
'id' => 'code_template',
]) ?>
<span class="input-group-btn">
<button id="copyTemplateCodeButton" type="button" class="btn btn-primary btn-flat"><i class="fa fa-files-o" aria-hidden="true"></i></button>
</span>
</div>
<?php
$code = Html::encode(
"[?= \core\widgets\menu\MenuWidget::widget([
'menu_id' => ".$menu->id.",
]) ?]");
$code = "[?= \core\widgets\menu\MenuWidget::widget(['menu_id' => " . $menu->id . ']) ?]';
?>
<p><?= Yii::t('menu', 'For editor') ?></p>
<pre><?= $code ?></pre>
<div class="input-group">
<?= Html::input('text', 'code_editor', $code, [
'class' => 'form-control',
'id' => 'code_editor',
]) ?>
<span class="input-group-btn">
<button id="copyEditorCodeButton" type="button" class="btn btn-primary btn-flat"><i class="fa fa-files-o" aria-hidden="true"></i></button>
</span>
</div>
</div>
</div>
</div>

5
common/behaviors/WidgetContentBehavior.php

@ -12,7 +12,8 @@ use yii\base\Behavior;
class WidgetContentBehavior extends Behavior
{
/**
* Parse Widgets [?= ... ?]
* Parse Widgets #?= ... ?#
*
* @param $text
*
* @return string
@ -23,8 +24,10 @@ class WidgetContentBehavior extends Behavior
$array = [];
$string = Html::decode($m[2]);
eval("\$array = $string;");
return $m[1]($array);
}, $text);
return $content;
}
}

47
common/modules/banners/views/manage/place/view.php

@ -11,6 +11,26 @@ use common\modules\banners\helpers\BannerHelper;
$this->title = $place->title;
$this->params['breadcrumbs'][] = ['label' => Yii::t('banners', 'Places'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
$js2 = <<<JS2
$("#copyEditorCodeButton").on('click', function(){
CopyToClipboard($('#code_editor'));
});
$("#copyTemplateCodeButton").on('click', function(){
CopyToClipboard($('#code_template'));
});
JS2;
$this->registerJs($js2, $this::POS_READY);
$js = <<<JS
function CopyToClipboard(selector) {
var body = $("body");
selector.select();
document.execCommand("copy");
}
JS;
$this->registerJs($js, $this::POS_HEAD);
?>
<div class="place-view">
@ -57,18 +77,33 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="box-body">
<?php
$code = Html::encode(
"<?= \common\modules\\banners\widgets\BannerWidget::widget(['id' => ".$place->id."]) ?>");
$code = "<?= \common\modules\\banners\widgets\BannerWidget::widget(['id' => " . $place->id . ']) ?>';
?>
<p><?= Yii::t('banners', 'For template') ?></p>
<pre><?= $code ?></pre>
<div class="input-group">
<?= Html::input('text', 'code_template', $code, [
'class' => 'form-control',
'id' => 'code_template',
]) ?>
<span class="input-group-btn">
<button id="copyTemplateCodeButton" type="button" class="btn btn-primary btn-flat"><i class="fa fa-files-o" aria-hidden="true"></i></button>
</span>
</div>
<?php
$code = Html::encode(
"[?= \common\modules\\banners\widgets\BannerWidget::widget(['id' => ".$place->id."]) ?]");
$code = "[?= \common\modules\\banners\widgets\BannerWidget::widget(['id' => " . $place->id . ']) ?]';
?>
<p><?= Yii::t('banners', 'For editor') ?></p>
<pre><?= $code ?></pre>
<div class="input-group">
<?= Html::input('text', 'code_editor', $code, [
'class' => 'form-control',
'id' => 'code_editor',
]) ?>
<span class="input-group-btn">
<button id="copyEditorCodeButton" type="button" class="btn btn-primary btn-flat"><i class="fa fa-files-o" aria-hidden="true"></i></button>
</span>
</div>
</div>
</div>
</div>

10
common/modules/forms/FormsModule.php

@ -2,12 +2,10 @@
namespace common\modules\forms;
use common\modules\forms\entities\Form;
use common\modules\forms\entities\FormMessage;
use common\modules\forms\urls\FormsUrlRule;
use core\components\modules\ModuleInterface;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
/**
* blog module definition class
@ -35,8 +33,12 @@ class FormsModule extends \yii\base\Module implements ModuleInterface
$app->controllerMap['migrate']['migrationPath'][] = '@common/modules/forms/migrations';
// prepare rules
//$app->getUrlManager()->addRules([
// 'forms/manage/form/view/<id:\d+>' => 'forms/manage/form/view',
//]);
$app->getUrlManager()->addRules([
'forms/manage/form/view/<id:\d+>' => 'forms/manage/form/view',
['class' => FormsUrlRule::class],
]);
// add languages

59
common/modules/forms/controllers/manage/FormController.php

@ -7,7 +7,6 @@ use common\modules\forms\forms\FormSearch;
use common\modules\forms\entities\Form;
use common\modules\pages\entities\Page;
use common\modules\forms\forms\FormForm;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
@ -17,12 +16,12 @@ use Yii;
class FormController extends Controller
{
private $service;
private $_service;
public function __construct($id, $module, FormManageService $service, $config = [])
{
parent::__construct($id, $module, $config);
$this->service = $service;
$this->_service = $service;
}
public function behaviors(): array
@ -85,7 +84,8 @@ class FormController extends Controller
$form = new FormForm();
if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try {
$form = $this->service->create($form);
$form = $this->_service->create($form);
return $this->redirect(['view', 'id' => $form->id]);
} catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e);
@ -111,7 +111,8 @@ class FormController extends Controller
$form = new FormForm($form_model);
if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try {
$this->service->edit($form_model->id, $form);
$this->_service->edit($form_model->id, $form);
return $this->redirect(['view', 'id' => $form_model->id]);
} catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e);
@ -127,16 +128,18 @@ class FormController extends Controller
/**
* @param integer $id
*
* @return mixed
*/
public function actionDelete($id)
{
try {
$this->service->remove($id);
$this->_service->remove($id);
} catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e);
Yii::$app->session->setFlash('error', $e->getMessage());
}
return $this->redirect(['index']);
}
@ -146,22 +149,54 @@ class FormController extends Controller
\Yii::$app->response->format = Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$data = Page::find()->select('id, title as text')->andWhere(['tree' => 1])->andWhere(['like', 'title', $q])->limit(20)->asArray()->all();
$out['results'] = array_values($data);
$data = [];
$pages = Page::find()
->with('translation')
->leftJoin('{{%pages_lng}}', '`pages_lng`.`page_id` = `pages`.`id`')
->andWhere(['like', 'pages_lng.title', $q])
->limit(20)
->all();
foreach ($pages as $page) {
$data[] = [
'id' => $page->id,
'text' => isset($page->translation) ? $page->translation->title : null,
];
}
elseif ($id > 0) {
$tag_name = Page::findOne($id)->title;
$out['results'] = array_values($data);
} elseif ($id > 0) {
$tag_name = Page::findOne($id)->translation->title;
$out['results'] = ['id' => $tag_name, 'text' => $tag_name];
} else {
/*$data = [];
$pages = Page::find()
->with('translation')
->leftJoin('{{%pages_lng}}', '`pages_lng`.`page_id` = `pages`.`id`')
->limit(20)
->all();
foreach ($pages as $page) {
$data[] = [
'id' => $page->id,
'text' => isset($page->translation) ? $page->translation->title : null,
];
}*/
$data = [];
$pages = Page::find()->typePublic()->orderBy(['id' => SORT_DESC])->limit(20)->all();
foreach ($pages as $page) {
$data[] = [
'id' => $page->id,
'text' => isset($page->translation) ? $page->translation->title : null,
];
}
else {
$data = Page::find()->select('id, title as text')->andWhere(['tree' => 1])->orderBy(['id' => SORT_DESC])->limit(20)->asArray()->all();
$out['results'] = array_values($data);
}
return $out;
}
/**
* @param integer $id
*
* @return Form the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/

41
common/modules/forms/urls/FormsUrlRule.php

@ -0,0 +1,41 @@
<?php
namespace common\modules\forms\urls;
use common\modules\forms\repositories\FormRepository;
use core\helpers\LanguageHelper;
use yii\base\BaseObject;
use yii\web\UrlRuleInterface;
use yii;
class FormsUrlRule extends BaseObject implements UrlRuleInterface
{
public $prefix = 'forms/form/send';
private $_repository;
public function __construct(FormRepository $repository, array $config = [])
{
parent::__construct($config);
$this->_repository = $repository;
}
public function parseRequest($manager, $request)
{
$uri = ltrim(LanguageHelper::processLangInUrl($request->pathInfo), '/');
if ($uri == $this->prefix) {
$id = Yii::$app->request->get('id');
$form = $this->_repository->get($id);
if ($form) {
return [$uri, ['id' => $id]];
}
}
return false;
}
public function createUrl($manager, $route, $params)
{
return false;
}
}

8
common/modules/forms/views/manage/form/_form/_form-builder.php

@ -10,10 +10,13 @@ use \yii\helpers\Json;
* @var $this \yii\web\View
* @var $model \common\modules\forms\forms\FormForm
*/
\backend\components\form_builder\assets\FormBuilderAsset::register($this);
$bundle = \backend\components\form_builder\assets\FormBuilderAsset::register($this);
$lng = str_replace('_', '-', Yii::$app->language);
$lng_file = $bundle->baseUrl . '/js/languages/';
$data = $model->data ? Json::encode($model->data, JSON_UNESCAPED_UNICODE) : '[]';
$js = <<<JS
var options = {
controlOrder: [
@ -25,7 +28,8 @@ $js = <<<JS
'number', 'autocomplete', 'date', 'file'
],
i18n: {
locale: '{$lng}'
locale: '{$lng}',
location: '{$lng_file}'
},
showActionButtons: false,
formData: {$data},

49
common/modules/forms/views/manage/form/view.php

@ -11,6 +11,26 @@ use common\modules\forms\helpers\FormHelper;
$this->title = $form->name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('forms', 'Forms'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
$js2 = <<<JS2
$("#copyEditorCodeButton").on('click', function(){
CopyToClipboard($('#code_editor'));
});
$("#copyTemplateCodeButton").on('click', function(){
CopyToClipboard($('#code_template'));
});
JS2;
$this->registerJs($js2, $this::POS_READY);
$js = <<<JS
function CopyToClipboard(selector) {
var body = $("body");
selector.select();
document.execCommand("copy");
}
JS;
$this->registerJs($js, $this::POS_HEAD);
?>
<div class="form-view">
@ -59,7 +79,7 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="box-header with-border"><?= Yii::t('forms', 'Complete Message') ?></div>
<div class="box-body">
<?= Yii::$app->formatter->asHtml($form->complete_text, [
'Attr.AllowedRel' => array('nofollow'),
'Attr.AllowedRel' => ['nofollow'],
'HTML.SafeObject' => true,
'Output.FlashCompat' => true,
'HTML.SafeIframe' => true,
@ -76,18 +96,33 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="box-body">
<?php
$code = Html::encode(
"<?= \common\modules\\forms\widgets\FormWidget::widget(['id' => ".$form->id."]) ?>");
$code = "<?= \common\modules\\forms\widgets\FormWidget::widget(['id' => " . $form->id . ']) ?>';
?>
<p><?= Yii::t('forms', 'For template') ?></p>
<pre><?= $code ?></pre>
<div class="input-group">
<?= Html::input('text', 'code_template', $code, [
'class' => 'form-control',
'id' => 'code_template',
]) ?>
<span class="input-group-btn">
<button id="copyTemplateCodeButton" type="button" class="btn btn-primary btn-flat"><i class="fa fa-files-o" aria-hidden="true"></i></button>
</span>
</div>
<?php
$code = Html::encode(
"[?= \common\modules\\forms\widgets\FormWidget::widget(['id' => ".$form->id."]) ?]");
$code = "[?= \common\modules\\forms\widgets\FormWidget::widget(['id' => " . $form->id . ']) ?]';
?>
<p><?= Yii::t('menu', 'For editor') ?></p>
<pre><?= $code ?></pre>
<div class="input-group">
<?= Html::input('text', 'code_editor', $code, [
'class' => 'form-control',
'id' => 'code_editor',
]) ?>
<span class="input-group-btn">
<button id="copyEditorCodeButton" type="button" class="btn btn-primary btn-flat"><i class="fa fa-files-o" aria-hidden="true"></i></button>
</span>
</div>
</div>
</div>
</div>

2
common/modules/pages/PagesModule.php

@ -6,7 +6,6 @@ use common\modules\pages\widgets\MenuItemCreatorWidget;
use core\components\modules\ModuleInterface;
use yii\helpers\ArrayHelper;
/**
* page module definition class
*/
@ -78,6 +77,7 @@ class PagesModule extends \yii\base\Module implements ModuleInterface
'menu_id' => $menu_id,
]),
];
return $widgets;
}
}

10
common/modules/pages/controllers/PageController.php

@ -7,17 +7,16 @@ use frontend\components\FrontendController;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
class PageController extends FrontendController
{
private $pages;
private $_pages;
public $layout = 'page';
public function __construct($id, $module, PageReadRepository $pages, $config = [])
{
parent::__construct($id, $module, $config);
$this->pages = $pages;
$this->_pages = $pages;
}
public function behaviors(): array
@ -47,13 +46,14 @@ class PageController extends FrontendController
/**
* @param $id
*
* @return mixed
* @throws NotFoundHttpException
* @internal param string $slug
*/
public function actionView($id)
{
if (!$page = $this->pages->find($id)) {
if (!$page = $this->_pages->find($id)) {
throw new NotFoundHttpException('The requested page does not exist.');
}
@ -64,7 +64,7 @@ class PageController extends FrontendController
public function actionPreview($id, $language = '')
{
if (!$page = $this->pages->findPreview($id, $language)) {
if (!$page = $this->_pages->findPreview($id, $language)) {
throw new NotFoundHttpException('The requested page does not exist.');
}

10
common/modules/pages/entities/Page.php

@ -27,8 +27,8 @@ use Yii;
* @method ActiveRecord findTranslation(string $language)
* @method void saveTranslations($translations)
*
* @property ActiveRecord[] translations
* @property ActiveRecord[] translation
* @property ActiveRecord[] $translations
* @property ActiveRecord[] $translation
*
* @property Page $parent
* @property Page[] $parents
@ -52,6 +52,7 @@ class Page extends ActiveRecord
$page->type = $type;
$page->_form = $form;
return $page;
}
@ -87,7 +88,7 @@ class Page extends ActiveRecord
'virtualClassName' => 'PagesVirtualTranslate',
'translatedLanguages' => \Yii::$app->params['translatedLanguages'],
'relativeField' => 'page_id',
'tableName' => "{{%pages_lng}}",
'tableName' => '{{%pages_lng}}',
'attributes' => ['title', 'content', 'meta_title', 'meta_description', 'meta_keywords'],
'defaultLanguage' => \Yii::$app->params['defaultLanguage'],
//'defaultLanguage' => basename(Yii::$app->getBasePath()) === 'backend' ? Yii::$app->language : Yii::$app->params['defaultLanguage'],
@ -110,7 +111,8 @@ class Page extends ActiveRecord
];
}
public function attributeLabels() {
public function attributeLabels()
{
return [
'title' => Yii::t('pages', 'Title'),
'slug' => Yii::t('pages', 'Slug'),

6
common/modules/pages/urls/PageMainUrlRule.php

@ -39,6 +39,7 @@ class PageMainUrlRule extends BaseObject implements UrlRuleInterface
if (!$post = $this->repository->findBySlug($this->getPathSlug($path))) {
return ['id' => null, 'path' => null];
}
return ['id' => $post->id, 'path' => $post->slug];
}, null, new TagDependency(['tags' => ['pages']]));
@ -52,6 +53,7 @@ class PageMainUrlRule extends BaseObject implements UrlRuleInterface
return ['pages/page/view', ['id' => $result['id']]];
}
return false;
}
@ -67,6 +69,7 @@ class PageMainUrlRule extends BaseObject implements UrlRuleInterface
if (!$page = $this->repository->find($id)) {
return null;
}
return $page->slug;
}, null, new TagDependency(['tags' => ['pages']]));
@ -74,14 +77,17 @@ class PageMainUrlRule extends BaseObject implements UrlRuleInterface
return '#';
//throw new InvalidArgumentException('Undefined id.');
}
return LanguageHelper::addLangToUrl($url, isset($params['language']) ? $params['language'] : null);
}
return false;
}
private function getPathSlug($path): string
{
$chunks = explode('/', $path);
return end($chunks);
}
}

7
frontend/components/FrontendController.php

@ -6,19 +6,18 @@
namespace frontend\components;
use yii\web\Cookie;
use yii\base\Theme;
use yii\web\Controller;
use Yii;
class FrontendController extends Controller
{
public function init() {
public function init()
{
parent::init();
// language
$languages = ['ru', 'en'];
$languages = \Yii::$app->params['translatedLanguages'];
$language = Yii::$app->request->get('language');
Yii::$app->language = $language && in_array($language, $languages) ? $language : Yii::$app->language;

Loading…
Cancel
Save