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. 59
      backend/views/menu/menu.php
  5. 11
      common/behaviors/WidgetContentBehavior.php
  6. 51
      common/modules/banners/views/manage/place/view.php
  7. 22
      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. 55
      common/modules/forms/views/manage/form/view.php
  12. 8
      common/modules/pages/PagesModule.php
  13. 10
      common/modules/pages/controllers/PageController.php
  14. 10
      common/modules/pages/entities/Page.php
  15. 22
      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; namespace backend\components\form_builder\assets;
use yii\jui\JuiAsset; use yii\jui\JuiAsset;
use yii\web\AssetBundle; 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 = Да

59
backend/views/menu/menu.php

@ -5,7 +5,6 @@
*/ */
use kartik\form\ActiveForm; use kartik\form\ActiveForm;
use yii\helpers\ArrayHelper;
use yii\helpers\Html; use yii\helpers\Html;
/** /**
@ -19,6 +18,26 @@ use yii\helpers\Html;
$this->title = Yii::t('menu', 'Menu'); $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'][] = Html::encode(isset($menu->translation) ? $menu->translation->name : Yii::t('menu', 'Not set'));
$this->params['breadcrumbs'][] = $this->title; $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"> <div class="menu">
@ -72,12 +91,13 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="panel-group" id="accordion"> <div class="panel-group" id="accordion">
<?php foreach ($creator as $item): ?> <?php foreach ($creator as $item) : ?>
<div class="panel panel-default"> <div class="panel panel-default">
<div class="panel-heading" style="padding-left: 0"> <div class="panel-heading" style="padding-left: 0">
<h4 class="panel-title"> <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> <i class="fa fa-angle-down pull-right" aria-hidden="true"></i></a>
</h4> </h4>
</div> </div>
@ -114,26 +134,37 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="box-body"> <div class="box-body">
<?php <?php
$code = Html::encode( $code = "<?= \core\widgets\menu\MenuWidget::widget(['menu_id' => " . $menu->id . ']) ?>';
"<?= \core\widgets\menu\MenuWidget::widget([
'menu_id' => ".$menu->id.",
]) ?>");
?> ?>
<p><?= Yii::t('menu', 'For template') ?></p> <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 <?php
$code = Html::encode( $code = "[?= \core\widgets\menu\MenuWidget::widget(['menu_id' => " . $menu->id . ']) ?]';
"[?= \core\widgets\menu\MenuWidget::widget([
'menu_id' => ".$menu->id.",
]) ?]");
?> ?>
<p><?= Yii::t('menu', 'For editor') ?></p> <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> </div>
</div> </div>
</div> </div>

11
common/behaviors/WidgetContentBehavior.php

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

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

@ -11,11 +11,31 @@ use common\modules\banners\helpers\BannerHelper;
$this->title = $place->title; $this->title = $place->title;
$this->params['breadcrumbs'][] = ['label' => Yii::t('banners', 'Places'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => Yii::t('banners', 'Places'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title; $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"> <div class="place-view">
<p> <p>
<?= Html::a(Yii::t('banners','Places'), ['index'], ['class' => 'btn btn-default']) ?> <?= Html::a(Yii::t('banners', 'Places'), ['index'], ['class' => 'btn btn-default']) ?>
<?= Html::a(Yii::t('buttons', 'Edit'), ['update', 'id' => $place->id], ['class' => 'btn btn-primary']) ?> <?= Html::a(Yii::t('buttons', 'Edit'), ['update', 'id' => $place->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('buttons', 'Delete'), ['delete', 'id' => $place->id], [ <?= Html::a(Yii::t('buttons', 'Delete'), ['delete', 'id' => $place->id], [
'class' => 'btn btn-danger', 'class' => 'btn btn-danger',
@ -41,7 +61,7 @@ $this->params['breadcrumbs'][] = $this->title;
[ [
'attribute' => 'active', 'attribute' => 'active',
'format' => 'raw', 'format' => 'raw',
'value' => function(BannerPlace $place) { 'value' => function (BannerPlace $place) {
return BannerHelper::statusLabel($place->active); return BannerHelper::statusLabel($place->active);
} }
], ],
@ -57,18 +77,33 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="box-body"> <div class="box-body">
<?php <?php
$code = Html::encode( $code = "<?= \common\modules\\banners\widgets\BannerWidget::widget(['id' => " . $place->id . ']) ?>';
"<?= \common\modules\\banners\widgets\BannerWidget::widget(['id' => ".$place->id."]) ?>");
?> ?>
<p><?= Yii::t('banners', 'For template') ?></p> <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 <?php
$code = Html::encode( $code = "[?= \common\modules\\banners\widgets\BannerWidget::widget(['id' => " . $place->id . ']) ?]';
"[?= \common\modules\\banners\widgets\BannerWidget::widget(['id' => ".$place->id."]) ?]");
?> ?>
<p><?= Yii::t('banners', 'For editor') ?></p> <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> </div>
</div> </div>

22
common/modules/forms/FormsModule.php

@ -2,12 +2,10 @@
namespace common\modules\forms; namespace common\modules\forms;
use common\modules\forms\entities\Form;
use common\modules\forms\entities\FormMessage; use common\modules\forms\entities\FormMessage;
use common\modules\forms\urls\FormsUrlRule;
use core\components\modules\ModuleInterface; use core\components\modules\ModuleInterface;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use yii\helpers\Html;
/** /**
* blog module definition class * blog module definition class
@ -35,8 +33,12 @@ class FormsModule extends \yii\base\Module implements ModuleInterface
$app->controllerMap['migrate']['migrationPath'][] = '@common/modules/forms/migrations'; $app->controllerMap['migrate']['migrationPath'][] = '@common/modules/forms/migrations';
// prepare rules // prepare rules
//$app->getUrlManager()->addRules([
// 'forms/manage/form/view/<id:\d+>' => 'forms/manage/form/view',
//]);
$app->getUrlManager()->addRules([ $app->getUrlManager()->addRules([
'forms/manage/form/view/<id:\d+>' => 'forms/manage/form/view', ['class' => FormsUrlRule::class],
]); ]);
// add languages // add languages
@ -50,21 +52,21 @@ class FormsModule extends \yii\base\Module implements ModuleInterface
// add menu items // add menu items
if (basename($app->getBasePath()) === 'backend') { if (basename($app->getBasePath()) === 'backend') {
$app->params['adminMenu'][] = [ $app->params['adminMenu'][] = [
'label' => \Yii::t( 'forms', 'Forms' ), 'label' => \Yii::t('forms', 'Forms'),
'icon' => 'address-card-o', 'icon' => 'address-card-o',
'items' => [ 'items' => [
[ [
'label' => \Yii::t( 'forms', 'Forms' ), 'label' => \Yii::t('forms', 'Forms'),
'icon' => 'caret-right', 'icon' => 'caret-right',
'url' => [ '/forms/manage/form/index' ] 'url' => ['/forms/manage/form/index']
], ],
[ [
'label' => \Yii::t( 'forms', 'Messages' ), 'label' => \Yii::t('forms', 'Messages'),
'icon' => 'caret-right', 'icon' => 'caret-right',
'url' => [ '/forms/manage/form-message/index' ] 'url' => ['/forms/manage/form-message/index']
], ],
], ],
'visible' => \Yii::$app->user->can( 'admin' ) || \Yii::$app->user->can( 'FormsManagement' ), 'visible' => \Yii::$app->user->can('admin') || \Yii::$app->user->can('FormsManagement'),
]; ];
} }

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\forms\entities\Form;
use common\modules\pages\entities\Page; use common\modules\pages\entities\Page;
use common\modules\forms\forms\FormForm; use common\modules\forms\forms\FormForm;
use yii\helpers\Json;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
@ -17,12 +16,12 @@ use Yii;
class FormController extends Controller class FormController extends Controller
{ {
private $service; private $_service;
public function __construct($id, $module, FormManageService $service, $config = []) public function __construct($id, $module, FormManageService $service, $config = [])
{ {
parent::__construct($id, $module, $config); parent::__construct($id, $module, $config);
$this->service = $service; $this->_service = $service;
} }
public function behaviors(): array public function behaviors(): array
@ -85,7 +84,8 @@ class FormController extends Controller
$form = new FormForm(); $form = new FormForm();
if ($form->load(Yii::$app->request->post()) && $form->validate()) { if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try { try {
$form = $this->service->create($form); $form = $this->_service->create($form);
return $this->redirect(['view', 'id' => $form->id]); return $this->redirect(['view', 'id' => $form->id]);
} catch (\DomainException $e) { } catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e); Yii::$app->errorHandler->logException($e);
@ -111,7 +111,8 @@ class FormController extends Controller
$form = new FormForm($form_model); $form = new FormForm($form_model);
if ($form->load(Yii::$app->request->post()) && $form->validate()) { if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try { try {
$this->service->edit($form_model->id, $form); $this->_service->edit($form_model->id, $form);
return $this->redirect(['view', 'id' => $form_model->id]); return $this->redirect(['view', 'id' => $form_model->id]);
} catch (\DomainException $e) { } catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e); Yii::$app->errorHandler->logException($e);
@ -127,16 +128,18 @@ class FormController extends Controller
/** /**
* @param integer $id * @param integer $id
*
* @return mixed * @return mixed
*/ */
public function actionDelete($id) public function actionDelete($id)
{ {
try { try {
$this->service->remove($id); $this->_service->remove($id);
} 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());
} }
return $this->redirect(['index']); return $this->redirect(['index']);
} }
@ -146,22 +149,54 @@ class FormController extends Controller
\Yii::$app->response->format = Response::FORMAT_JSON; \Yii::$app->response->format = Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']]; $out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) { if (!is_null($q)) {
$data = Page::find()->select('id, title as text')->andWhere(['tree' => 1])->andWhere(['like', 'title', $q])->limit(20)->asArray()->all(); $data = [];
$out['results'] = array_values($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) { $out['results'] = array_values($data);
$tag_name = Page::findOne($id)->title; } elseif ($id > 0) {
$tag_name = Page::findOne($id)->translation->title;
$out['results'] = ['id' => $tag_name, 'text' => $tag_name]; $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); $out['results'] = array_values($data);
} }
return $out; return $out;
} }
/** /**
* @param integer $id * @param integer $id
*
* @return Form the loaded model * @return Form the loaded model
* @throws NotFoundHttpException if the model cannot be found * @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 $this \yii\web\View
* @var $model \common\modules\forms\forms\FormForm * @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 = str_replace('_', '-', Yii::$app->language);
$lng_file = $bundle->baseUrl . '/js/languages/';
$data = $model->data ? Json::encode($model->data, JSON_UNESCAPED_UNICODE) : '[]'; $data = $model->data ? Json::encode($model->data, JSON_UNESCAPED_UNICODE) : '[]';
$js = <<<JS $js = <<<JS
var options = { var options = {
controlOrder: [ controlOrder: [
@ -25,7 +28,8 @@ $js = <<<JS
'number', 'autocomplete', 'date', 'file' 'number', 'autocomplete', 'date', 'file'
], ],
i18n: { i18n: {
locale: '{$lng}' locale: '{$lng}',
location: '{$lng_file}'
}, },
showActionButtons: false, showActionButtons: false,
formData: {$data}, formData: {$data},

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

@ -11,11 +11,31 @@ use common\modules\forms\helpers\FormHelper;
$this->title = $form->name; $this->title = $form->name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('forms', 'Forms'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => Yii::t('forms', 'Forms'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title; $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"> <div class="form-view">
<p> <p>
<?= Html::a(Yii::t('forms','Forms'), ['index'], ['class' => 'btn btn-default']) ?> <?= Html::a(Yii::t('forms', 'Forms'), ['index'], ['class' => 'btn btn-default']) ?>
<?= Html::a(Yii::t('buttons', 'Edit'), ['update', 'id' => $form->id], ['class' => 'btn btn-primary']) ?> <?= Html::a(Yii::t('buttons', 'Edit'), ['update', 'id' => $form->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('buttons', 'Delete'), ['delete', 'id' => $form->id], [ <?= Html::a(Yii::t('buttons', 'Delete'), ['delete', 'id' => $form->id], [
'class' => 'btn btn-danger', 'class' => 'btn btn-danger',
@ -44,7 +64,7 @@ $this->params['breadcrumbs'][] = $this->title;
[ [
'attribute' => 'status', 'attribute' => 'status',
'format' => 'raw', 'format' => 'raw',
'value' => function(Form $form) { 'value' => function (Form $form) {
return FormHelper::statusLabel($form->status); return FormHelper::statusLabel($form->status);
} }
], ],
@ -59,11 +79,11 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="box-header with-border"><?= Yii::t('forms', 'Complete Message') ?></div> <div class="box-header with-border"><?= Yii::t('forms', 'Complete Message') ?></div>
<div class="box-body"> <div class="box-body">
<?= Yii::$app->formatter->asHtml($form->complete_text, [ <?= Yii::$app->formatter->asHtml($form->complete_text, [
'Attr.AllowedRel' => array('nofollow'), 'Attr.AllowedRel' => ['nofollow'],
'HTML.SafeObject' => true, 'HTML.SafeObject' => true,
'Output.FlashCompat' => true, 'Output.FlashCompat' => true,
'HTML.SafeIframe' => true, 'HTML.SafeIframe' => true,
'URI.SafeIframeRegexp'=>'%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%', 'URI.SafeIframeRegexp' => '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%',
]) ?> ]) ?>
</div> </div>
</div> </div>
@ -76,18 +96,33 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="box-body"> <div class="box-body">
<?php <?php
$code = Html::encode( $code = "<?= \common\modules\\forms\widgets\FormWidget::widget(['id' => " . $form->id . ']) ?>';
"<?= \common\modules\\forms\widgets\FormWidget::widget(['id' => ".$form->id."]) ?>");
?> ?>
<p><?= Yii::t('forms', 'For template') ?></p> <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 <?php
$code = Html::encode( $code = "[?= \common\modules\\forms\widgets\FormWidget::widget(['id' => " . $form->id . ']) ?]';
"[?= \common\modules\\forms\widgets\FormWidget::widget(['id' => ".$form->id."]) ?]");
?> ?>
<p><?= Yii::t('menu', 'For editor') ?></p> <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> </div>
</div> </div>

8
common/modules/pages/PagesModule.php

@ -6,7 +6,6 @@ use common\modules\pages\widgets\MenuItemCreatorWidget;
use core\components\modules\ModuleInterface; use core\components\modules\ModuleInterface;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
/** /**
* page module definition class * page module definition class
*/ */
@ -60,10 +59,10 @@ class PagesModule extends \yii\base\Module implements ModuleInterface
// add menu items // add menu items
if (basename($app->getBasePath()) === 'backend') { if (basename($app->getBasePath()) === 'backend') {
$app->params['adminMenu'][] = [ $app->params['adminMenu'][] = [
'label' => \Yii::t( 'pages', 'Pages' ), 'label' => \Yii::t('pages', 'Pages'),
'icon' => 'file-o', 'icon' => 'file-o',
'url' => [ '/pages/manage/page/index' ], 'url' => ['/pages/manage/page/index'],
'visible' => \Yii::$app->user->can( 'admin' ) || \Yii::$app->user->can( 'PagesManagement' ) 'visible' => \Yii::$app->user->can('admin') || \Yii::$app->user->can('PagesManagement')
]; ];
} }
} }
@ -78,6 +77,7 @@ class PagesModule extends \yii\base\Module implements ModuleInterface
'menu_id' => $menu_id, 'menu_id' => $menu_id,
]), ]),
]; ];
return $widgets; return $widgets;
} }
} }

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

@ -7,17 +7,16 @@ use frontend\components\FrontendController;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\AccessControl; use yii\filters\AccessControl;
class PageController extends FrontendController class PageController extends FrontendController
{ {
private $pages; private $_pages;
public $layout = 'page'; public $layout = 'page';
public function __construct($id, $module, PageReadRepository $pages, $config = []) public function __construct($id, $module, PageReadRepository $pages, $config = [])
{ {
parent::__construct($id, $module, $config); parent::__construct($id, $module, $config);
$this->pages = $pages; $this->_pages = $pages;
} }
public function behaviors(): array public function behaviors(): array
@ -47,13 +46,14 @@ class PageController extends FrontendController
/** /**
* @param $id * @param $id
*
* @return mixed * @return mixed
* @throws NotFoundHttpException * @throws NotFoundHttpException
* @internal param string $slug * @internal param string $slug
*/ */
public function actionView($id) 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.'); throw new NotFoundHttpException('The requested page does not exist.');
} }
@ -64,7 +64,7 @@ class PageController extends FrontendController
public function actionPreview($id, $language = '') 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.'); 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 ActiveRecord findTranslation(string $language)
* @method void saveTranslations($translations) * @method void saveTranslations($translations)
* *
* @property ActiveRecord[] translations * @property ActiveRecord[] $translations
* @property ActiveRecord[] translation * @property ActiveRecord[] $translation
* *
* @property Page $parent * @property Page $parent
* @property Page[] $parents * @property Page[] $parents
@ -52,6 +52,7 @@ class Page extends ActiveRecord
$page->type = $type; $page->type = $type;
$page->_form = $form; $page->_form = $form;
return $page; return $page;
} }
@ -87,7 +88,7 @@ class Page extends ActiveRecord
'virtualClassName' => 'PagesVirtualTranslate', 'virtualClassName' => 'PagesVirtualTranslate',
'translatedLanguages' => \Yii::$app->params['translatedLanguages'], 'translatedLanguages' => \Yii::$app->params['translatedLanguages'],
'relativeField' => 'page_id', 'relativeField' => 'page_id',
'tableName' => "{{%pages_lng}}", 'tableName' => '{{%pages_lng}}',
'attributes' => ['title', 'content', 'meta_title', 'meta_description', 'meta_keywords'], 'attributes' => ['title', 'content', 'meta_title', 'meta_description', 'meta_keywords'],
'defaultLanguage' => \Yii::$app->params['defaultLanguage'], 'defaultLanguage' => \Yii::$app->params['defaultLanguage'],
//'defaultLanguage' => basename(Yii::$app->getBasePath()) === 'backend' ? Yii::$app->language : 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 [ return [
'title' => Yii::t('pages', 'Title'), 'title' => Yii::t('pages', 'Title'),
'slug' => Yii::t('pages', 'Slug'), 'slug' => Yii::t('pages', 'Slug'),

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

@ -35,23 +35,25 @@ class PageMainUrlRule extends BaseObject implements UrlRuleInterface
if (preg_match('#^' . $this->prefix . '([0-9a-z_\-]*)$#is', $uri, $matches)) { if (preg_match('#^' . $this->prefix . '([0-9a-z_\-]*)$#is', $uri, $matches)) {
$path = $matches['1']; $path = $matches['1'];
$result = $this->cache->getOrSet( [ 'page_main_route', 'path' => $path ], function () use ( $path ) { $result = $this->cache->getOrSet(['page_main_route', 'path' => $path], function () use ($path) {
if ( ! $post = $this->repository->findBySlug($this->getPathSlug( $path ) ) ) { if (!$post = $this->repository->findBySlug($this->getPathSlug($path))) {
return [ 'id' => null, 'path' => null ]; return ['id' => null, 'path' => null];
} }
return [ 'id' => $post->id, 'path' => $post->slug ];
}, null, new TagDependency(['tags' => ['pages']]) );
if ( empty( $result['id'] ) ) { return ['id' => $post->id, 'path' => $post->slug];
}, null, new TagDependency(['tags' => ['pages']]));
if (empty($result['id'])) {
return false; return false;
} }
if ( $path != $result['path'] ) { if ($path != $result['path']) {
throw new UrlNormalizerRedirectException( [ 'pages/page/view', 'id' => $result['id'] ], 301 ); throw new UrlNormalizerRedirectException(['pages/page/view', 'id' => $result['id']], 301);
} }
return ['pages/page/view', ['id' => $result['id']]]; return ['pages/page/view', ['id' => $result['id']]];
} }
return false; return false;
} }
@ -67,6 +69,7 @@ class PageMainUrlRule extends BaseObject implements UrlRuleInterface
if (!$page = $this->repository->find($id)) { if (!$page = $this->repository->find($id)) {
return null; return null;
} }
return $page->slug; return $page->slug;
}, null, new TagDependency(['tags' => ['pages']])); }, null, new TagDependency(['tags' => ['pages']]));
@ -74,14 +77,17 @@ class PageMainUrlRule extends BaseObject implements UrlRuleInterface
return '#'; return '#';
//throw new InvalidArgumentException('Undefined id.'); //throw new InvalidArgumentException('Undefined id.');
} }
return LanguageHelper::addLangToUrl($url, isset($params['language']) ? $params['language'] : null); return LanguageHelper::addLangToUrl($url, isset($params['language']) ? $params['language'] : null);
} }
return false; return false;
} }
private function getPathSlug($path): string private function getPathSlug($path): string
{ {
$chunks = explode('/', $path); $chunks = explode('/', $path);
return end($chunks); return end($chunks);
} }
} }

7
frontend/components/FrontendController.php

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

Loading…
Cancel
Save