Fix blocks

parent 7409fd42
<?php
namespace common\modules\content\components;
use Yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use common\modules\content\models\CoBlocksLang;
class CoBlocksLangBehavior extends Behavior
{
public function events()
{
return [
ActiveRecord::EVENT_AFTER_UPDATE => 'Save',
ActiveRecord::EVENT_AFTER_INSERT => 'Insert',
ActiveRecord::EVENT_AFTER_DELETE => 'Delete',
];
}
public function Save($event)
{
$langs = Yii::$app->request->post('CoBlocksLang');
if ($langs)
{
foreach ($langs as $lang_id => $attributes)
{
$lang = CoBlocksLang::find()->where([
'block_id' => $this->owner->id,
'lang_id' => $lang_id,
])->one();
if (!$lang)
{
$lang = new CoBlocksLang;
}
$attributes['block_id'] = $this->owner->id;
$attributes['lang_id'] = $lang_id;
$lang->setAttributes( $attributes );
if(!$lang->save()) die(print_r($lang->errors));
}
}
return true;
}
public function Insert($event)
{
$langs = Yii::$app->request->post('CoBlocksLang');
if ($langs)
{
foreach ($langs as $lang_id => $attributes)
{
$meta_tag = new CoBlocksLang;
$attributes['block_id'] = $this->owner->id;
$attributes['lang_id'] = $lang_id;
$meta_tag->setAttributes($attributes);
$meta_tag->save(false);
}
}
return true;
}
public function Delete($event)
{
CoBlocksLang::deleteAll([
'block_id' => $this->owner->id
]);
return true;
}
}
......@@ -3,12 +3,15 @@
namespace common\modules\content\controllers;
use Yii;
use common\modules\content\models\CoBlocks;
use common\modules\content\models\SearchCoBlocks;
use common\components\AdminController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\modules\content\models\CoBlocks;
use common\modules\content\models\CoBlocksLang;
use common\modules\content\models\SearchCoBlocks;
use common\modules\languages\models\Languages;
/**
* BlockAdminController implements the CRUD actions for CoBlocks model.
*/
......@@ -21,9 +24,6 @@ class BlockAdminController extends AdminController
'Update' => 'Редактирование контента',
'Delete' => 'Удаление контента',
'View' => 'Просмотр контента',
'Createcontent' => 'Добавление данных контента',
'Updatecontent' => 'Редактирование данных контента',
'Deletecontent' => 'Удаление данных контента',
];
}
......@@ -78,7 +78,48 @@ class BlockAdminController extends AdminController
*/
public function actionCreate()
{
return $this->actionUpdate();
$model = new CoBlocks;
$langs = [];
foreach (Languages::find()->all() as $lang)
{
$lng = new CoBlocksLang;
$lng->lang_id = $lang->id;
$langs[$lang->id] = $lng;
}
Yii::$app->controller->page_title = 'Добавить блок';
Yii::$app->controller->breadcrumbs = [
['Управление блоками' => \yii\helpers\Url::toRoute('manage')],
'Добавить блок',
];
if (Yii::$app->request->isPost)
{
$transaction = Yii::$app->db->beginTransaction();
try
{
$model->attributes = Yii::$app->request->post('CoBlocks');
if($model->save())
{
$transaction->commit();
return $this->redirect(['manage']);
}
}
catch (\Exception $e)
{
$transaction->rollBack();
throw $e;
}
}
return $this->render('create', [
'model' => $model,
'langs' => $langs
]);
}
/**
......@@ -87,34 +128,58 @@ class BlockAdminController extends AdminController
* @param string $id
* @return mixed
*/
public function actionUpdate($id=null)
public function actionUpdate($id)
{
if(empty($id)){
$model = new CoBlocks();
\yii::$app->controller->page_title = 'Создание блока';
\yii::$app->controller->breadcrumbs = [
['Список блоков' => \yii\helpers\Url::toRoute('manage')],
'Создание блока'
];
}
else {
$model = $this->findModel($id);
\yii::$app->controller->page_title = 'Редактирование блока';
\yii::$app->controller->breadcrumbs = [
['Список блоков' => \yii\helpers\Url::toRoute('manage')],
'Редактирование блока'
];
$langs = [];
foreach (Languages::find()->all() as $lang)
{
$lng = $model->getLang($lang->id)->one();
if(!$lng)
{
$lng = new CoBlocksLang;
$lng->lang_id = $lang->id;
}
$langs[$lang->id] = $lng;
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->controller->page_title = 'Редактировать блок';
Yii::$app->controller->breadcrumbs = [
['Управление блоками' => \yii\helpers\Url::toRoute('manage')],
'Редактировать блок',
];
if (Yii::$app->request->isPost)
{
$transaction = Yii::$app->db->beginTransaction();
try
{
$model->attributes = Yii::$app->request->post('CoBlocks');
if($model->save())
{
$transaction->commit();
return $this->redirect(['manage']);
} else {
$form = new \common\components\BaseForm('/common/modules/content/forms/BlockForm', $model);
}
}
catch (\Exception $e)
{
$transaction->rollBack();
throw $e;
}
}
return $this->render('update', [
'model' => $model,
'form' => $form->out,
'langs' => $langs
]);
}
}
/**
* Deletes an existing CoBlocks model.
......
......@@ -182,7 +182,7 @@ class ContentAdminController extends AdminController
$meta[$lang->id] = $mt;
$lng = $model->getContent($lang->id)->one();
$lng = $model->getLang($lang->id)->one();
if(!$lng)
{
......
......@@ -33,7 +33,7 @@ class PageController extends \common\components\BaseController
$model = CoContent::findOne(['url' => $page]);
}
$content = $model->content->content;
$content = $model->lang->content;
$this->meta_title = $model->metaTag->title . ' - ' . \Yii::$app->params['name'];
$this->meta_description = $model->metaTag->description;
$this->meta_keywords = $model->metaTag->keywords;
......
<?php
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use \common\modules\content\models\CoContent;
$blocks = \common\modules\content\models\CoBlocks::find()->all();
$block_hint = '';
if(count($blocks)) {
$block_hint .= "<ul>\n";
foreach($blocks as $block) {
$block_hint .= "<li>{{$block->name}} {$block->title}</li>\n";
}
$block_hint .= "</ul>\n";
}
return [
'activeForm'=>[
'id' => 'controller-form',
'options' => [
'enctype' => 'multipart/form-data'
],
],
'elements' => [
'category_id' => [
'type' => 'dropdownlist',
'items' => ArrayHelper::map(\common\modules\content\models\CoCategory::find()->all(), 'id', 'name'),
'empty' => 'Без привязки к категории',
'class' => 'form-control',
'hint' => 'Для того что бы было проще сортировать данную страницу в общем списке вы можете привязать ее к определенной категории. Список категории настраивается
' . Html::a('тут',['/content/category-admin/manage']) . '.',
],
'url' => [
'type' => 'text',
'class' => 'form-control',
'hint' => 'Для создания ЧПУ («Человеку Понятный Урл») укажите латинскими буквами путь, например, razdel/podrazdel/nazvanie_stranici.html ',
],
'name' => [
'type' => 'text',
'class' => 'form-control',
'hint' => 'Название страницы не будет отображаться пользователям сайта и служит исключительно для служебного пользования в Панель управления.',
],
'title' => [
'type' => 'text',
'class' => 'form-control',
'hint' => 'Заголовок страницы виден пользователю сайта и как правило оформляется в тег &lt;h1&gt;. Если дизайном страницы не предусмотрен вывод заголовка, то он не будет выводиться даже если был введен в данное поле.',
],
($model->preview?Html::img(\Yii::$app->params['frontUrl'] . CoContent::PHOTO_FOLDER . $model->preview):''),
'image' => ['type' => 'file', 'class' => 'form-control',],
'text' => [
'type' => 'textarea',
'class' => 'form-control',
'label' => 'Текст редактируемый на странице<br>'.$block_hint,
],
'active' => [
'type' => 'checkbox',
'template' => '{input}<a href="#" class="btn btn-xs btn-success m-l-5 disabled">Страница скрыта от пользователя / Страница видна пользователю</a>',
'opts' => [
'data-theme' => 'self',
// 'data-secondary-color' => "#79C137",
'data-render' => "switchery",
'label' => ' ',
],
],
// 'created_at' => ['type' => 'text', 'class' => 'form-control'],
// 'updated_at' => ['type' => 'text', 'class' => 'form-control'],
],
'buttons' => [
'submit' => ['type' => 'submit', 'value' => 'Cохранить']
]
];
......@@ -25,10 +25,23 @@ class CoBlocks extends \common\components\ActiveRecordModel
return 'co_blocks';
}
public function name() {
public function name()
{
return 'Блоки';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'langs' => [
'class' => 'common\modules\content\components\CoBlocksLangBehavior',
]
];
}
/**
* @inheritdoc
*/
......@@ -62,7 +75,7 @@ class CoBlocks extends \common\components\ActiveRecordModel
];
}
public function getContent($lang_id = null)
public function getLang($lang_id = null)
{
$lang_id = ($lang_id === null)? Languages::getCurrent()->id: $lang_id;
......
......@@ -4,6 +4,8 @@ namespace common\modules\content\models;
use Yii;
use common\modules\languages\models\Languages;
/**
* This is the model class for table "co_blocks_lang".
*
......@@ -27,17 +29,29 @@ class CoBlocksLang extends \common\components\ActiveRecordModel
return 'co_blocks_lang';
}
public function name()
{
return 'Языковые блоки';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['block_id', 'lang_id', 'name', 'title'], 'required'],
[['block_id', 'lang_id',], 'required'],
[['block_id', 'lang_id'], 'integer'],
[['text'], 'string'],
[['name'], 'string', 'max' => 50],
[['title'], 'string', 'max' => 250],
[['block_id'], 'exist', 'skipOnError' => true, 'targetClass' => CoBlocks::className(), 'targetAttribute' => ['block_id' => 'id']],
[['lang_id'], 'exist', 'skipOnError' => true, 'targetClass' => Languages::className(), 'targetAttribute' => ['lang_id' => 'id']],
];
......@@ -52,9 +66,7 @@ class CoBlocksLang extends \common\components\ActiveRecordModel
'id' => 'ID',
'block_id' => 'Block ID',
'lang_id' => 'Lang ID',
'name' => 'Name',
'title' => 'Title',
'text' => 'Text',
'text' => 'Текст',
];
}
......
......@@ -127,7 +127,7 @@ class CoContent extends \common\components\ActiveRecordModel
return $this->hasOne(CoCategory::className(), ['id' => 'category_id']);
}
public function getContent($lang_id = null)
public function getLang($lang_id = null)
{
$lang_id = ($lang_id === null)? Languages::getCurrent()->id: $lang_id;
......
......@@ -2,28 +2,79 @@
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use common\modules\content\models\CoBlocks;
/* @var $this yii\web\View */
/* @var $model common\modules\content\models\CoBlocks */
/* @var $form yii\widgets\ActiveForm */
$this->registerJsFile('/plugins/tinymce/js/tinymce/tinymce.min.js', ['position' => \yii\web\View::POS_END ]);
$js = <<<JS
tinymce.init({
selector: "textarea",theme: "modern",
language: "ru_RU",
custom_elements: "emstart,emend,header,main,span",
extended_valid_elements: "span[id|name|class|style],i[id|name|class|style],ul[id|name|class|style],li[id|name|class|style]",
height: '350px',
menubar: "edit insert view format table tools",
plugins: [
"advlist autolink link image code lists charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars insertdatetime media nonbreaking",
"table contextmenu directionality emoticons paste textcolor responsivefilemanager"
],
toolbar1: "undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | styleselect",
toolbar2: "| responsivefilemanager | link unlink anchor | image media | forecolor backcolor | print preview code ",
image_advtab: true ,
forced_root_block : false,
external_filemanager_path:"/filemanager/",
filemanager_title:"Responsive Filemanager" ,
external_plugins: { "filemanager" : "/filemanager/plugin.min.js"}
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY, 'tinymceLoad');
?>
<div class="co-blocks-form">
<div class="co-content-form">
<?php $form = ActiveForm::begin(); ?>
<?php $form = ActiveForm::begin([
'options' => [
'enctype' => 'multipart/form-data'
]
]); ?>
<?= $form->field($model, 'lang')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'category_id')->dropDownList(ArrayHelper::map(\common\modules\content\models\CoCategory::find()->all(), 'id', 'name'), [
'prompt' => 'Без привязки к категории',
'class' => 'form-control',
])->hint('Для того что бы было проще сортировать данную страницу в общем списке вы можете привязать ее к определенной категории. Список категории настраивается ' . Html::a('тут',['/content/category-admin/manage']) . '.') ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 250])->hint('Название страницы не будет отображаться пользователям сайта и служит исключительно для служебного пользования в Панель управления.') ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => 250])->hint('Заголовок страницы виден пользователю сайта и как правило оформляется в тег &lt;h1&gt;. Если дизайном страницы не предусмотрен вывод заголовка, то он не будет выводиться даже если был введен в данное поле.') ?>
<?= $form->field($model, 'text')->textarea(['rows' => 6]) ?>
<ul class="nav nav-pills">
<?php $c = 0; foreach ($langs as $i => $block) : $c++; ?>
<li class="<?=($c==1?'active':'')?>"><a href="#lang-<?=$block->lang->url?>" data-toggle="tab"><?=$block->lang->name?></a></li>
<?php endforeach; ?>
</ul>
<?= $form->field($model, 'date_create')->textInput() ?>
<div class="tab-content">
<?php $c = 0; foreach ($langs as $block) : $c++;
$lang_id = $block->lang->id; ?>
<div class="tab-pane fade <?=($c==1?'active in':'')?>" id="lang-<?=$block->lang->url;?>">
<?= $form->field($block, '['.$lang_id.']text')->textArea() ?>
</div>
<?php endforeach; ?>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('reviews', 'Create') : Yii::t('reviews', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
......
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model common\modules\content\models\SearchCoBlocks */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="co-blocks-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'lang') ?>
<?= $form->field($model, 'title') ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'text') ?>
<?php // echo $form->field($model, 'date_create') ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('reviews', 'Search'), ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton(Yii::t('reviews', 'Reset'), ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
echo $form;
\ No newline at end of file
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\modules\content\models\CoBlocks */
$this->title = Yii::t('content', 'Create Co Blocks');
$this->params['breadcrumbs'][] = ['label' => Yii::t('content', 'Co Blocks'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="co-blocks-create">
<?= $this->render('_form', [
'model' => $model,
'langs' => $langs
]) ?>
</div>
<?php
echo $form;
\ No newline at end of file
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\modules\content\models\CoBlocks */
$this->title = Yii::t('content', 'Update Co Blocks');
$this->params['breadcrumbs'][] = ['label' => Yii::t('content', 'Co Blocks'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="co-blocks-update">
<?= $this->render('_form', [
'model' => $model,
'langs' => $langs
]) ?>
</div>
<?php
use yii\db\Schema;
use yii\db\Migration;
class m160203_080816_fix_content extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->dropColumn('co_blocks_lang', 'name');
$this->dropColumn('co_blocks_lang', 'title');
$this->dropColumn('co_content', 'name');
$this->dropColumn('co_content', 'title');
$this->dropColumn('co_content', 'text');
}
public function safeDown()
{
$this->addColumn('co_blocks_lang', 'name', Schema::TYPE_STRING.'(50) NOT NULL');
$this->addColumn('co_blocks_lang', 'title', Schema::TYPE_STRING.'(250) NOT NULL');
$this->addColumn('co_content', 'name', Schema::TYPE_STRING.'(250) NOT NULL');
$this->addColumn('co_content', 'title', Schema::TYPE_STRING.'(250) NOT NULL');
$this->addColumn('co_content', 'text', 'longtext DEFAULT NULL');
}
}
......@@ -99,7 +99,7 @@ class SiteController extends BaseController
{
$model = \common\modules\content\models\CoContent::findOne(['url' => 'site/error']);
$content = $model->content->content;
$content = $model->lang->content;
$this->meta_title = $model->metaTag->title . ' - ' . \Yii::$app->params['name'];
$this->meta_description = $model->metaTag->description;
$this->meta_keywords = $model->metaTag->keywords;
......
......@@ -14,7 +14,7 @@ $models = CoContent::find()
<div class="col-md-6 col-xs-6 col-sm-12">
<div class="keys_block_small">
<img src="<?=CoContent::PHOTO_FOLDER . $model->preview?>" height="338" width="455">
<div class="keys_small_title"><?=$model->title?></div>
<div class="keys_small_title"><?=$model->lang->title?></div>
<div class="keys_small_foot">
<?=Html::a('<span>Подробнее</span>', ['/'.$model->url], ['class' => 'keys_small_btn_more'])?>
<!-- <a href="#" class="keys_small_tags"># Big data</a> -->
......
......@@ -21,8 +21,8 @@ $cases = CoContent::find()->where(['category_id' => 4]);
<?php foreach ($models as $model) : ?>
<div>
<div class="others_project">
<span class="others_project__subtitle"><?=$model->title?></span>
<p class="others_project__txt"><?=$model->text?></p>
<span class="others_project__subtitle"><?=$model->lang->title?></span>
<p class="others_project__txt"><?=$model->lang->text?></p>
<a href="<?=Url::to(['/' . $model->url])?>" class="others_project__bt">Подробнее</a>
<a href="<?=Url::to(['/case'])?>" class="others_project__link">Все проекты (<?=$cases->count();?>)</a>
</div>
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment