From 68e726516f98676897e110db1face144d6d4d143 Mon Sep 17 00:00:00 2001 From: Anastasia Date: Tue, 5 Jun 2018 12:08:41 +0300 Subject: [PATCH] - blog - edit comments --- backend/views/comment/_form.php | 8 +++++--- common/models/Comment.php | 13 ++++++++++--- common/models/Service.php | 2 +- common/models/blog/Article.php | 7 ++++++- console/migrations/m180605_072337_alter_table_comment.php | 44 ++++++++++++++++++++++++++++++++++++++++++++ console/migrations/m180605_082938_alter_table_article.php | 40 ++++++++++++++++++++++++++++++++++++++++ frontend/config/main.php | 6 ++++-- frontend/controllers/BlogController.php | 58 ++++++++++++++++++++++++---------------------------------- frontend/controllers/SiteController.php | 2 +- frontend/views/blog/_article.php | 90 ++++++++++++++++++++++++------------------------------------------------------------------ frontend/views/blog/index.php | 180 +++++++++++++++++++++++++----------------------------------------------------------------------------------------------------------------------------------------------------------- frontend/views/blog/view.php | 127 +++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------ frontend/views/service/view.php | 10 +++++++--- frontend/views/site/comments.php | 6 +++--- 14 files changed, 249 insertions(+), 344 deletions(-) create mode 100644 console/migrations/m180605_072337_alter_table_comment.php create mode 100644 console/migrations/m180605_082938_alter_table_article.php diff --git a/backend/views/comment/_form.php b/backend/views/comment/_form.php index e61235f..c9107f3 100644 --- a/backend/views/comment/_form.php +++ b/backend/views/comment/_form.php @@ -30,9 +30,11 @@ JS; - field($model, 'service_id')->dropDownList($services, [ - 'class' => 'select_service' - ])?> + entityObject !== null){ + $model->entityObject->language->title; + } + ?> field($model, 'name') ->textInput([ 'maxlength' => true ]) ?> diff --git a/common/models/Comment.php b/common/models/Comment.php index b8fbb99..93b8b9c 100644 --- a/common/models/Comment.php +++ b/common/models/Comment.php @@ -47,7 +47,7 @@ { return [ [ - [ 'comment' ], + [ 'comment', 'entity' ], 'string', ], [ @@ -59,7 +59,7 @@ ], [ [ - 'service_id', + 'entity_id', 'created_at', 'updated_at', ], @@ -68,7 +68,7 @@ ], [ [ - 'service_id', + 'entity_id', 'created_at', 'updated_at', ], @@ -111,4 +111,11 @@ 'updated_at' => Yii::t('app', 'Updated At'), ]; } + + public function getEntityObject(){ + if ($this->entity !== null){ + return $this->hasOne($this->entity, ['id' => 'entity_id']); + } + return null; + } } diff --git a/common/models/Service.php b/common/models/Service.php index dda08ad..c62aff9 100644 --- a/common/models/Service.php +++ b/common/models/Service.php @@ -155,7 +155,7 @@ class Service extends ActiveRecord } public function getComments(){ - return $this->hasMany(Comment::className(), ['service_id' => 'id']); + return $this->hasMany(Comment::className(), ['entity_id' => 'id'])->andWhere(['entity' => Service::className()]); } public function getQuestions(){ diff --git a/common/models/blog/Article.php b/common/models/blog/Article.php index 34d8789..f3fac93 100755 --- a/common/models/blog/Article.php +++ b/common/models/blog/Article.php @@ -4,7 +4,7 @@ use artbox\core\models\Image; use artbox\core\models\traits\AliasableTrait; - use artbox\webcomment\models\CommentModel; + use common\models\Comment; use yii\behaviors\TimestampBehavior; use yii\db\ActiveRecord; use artbox\core\models\Language; @@ -107,6 +107,7 @@ 'sort', 'author_id', 'image_id', + 'views' ], 'integer', ], @@ -262,4 +263,8 @@ return $this->hasMany(Tag::className(), [ 'id' => 'blog_tag_id' ]) ->viaTable('blog_article_to_tag', [ 'blog_article_id' => 'id' ]); } + + public function getComments(){ + return $this->hasMany(Comment::className(), ['entity_id' => 'id'])->andWhere(['entity' => Article::className()]); + } } diff --git a/console/migrations/m180605_072337_alter_table_comment.php b/console/migrations/m180605_072337_alter_table_comment.php new file mode 100644 index 0000000..26a2112 --- /dev/null +++ b/console/migrations/m180605_072337_alter_table_comment.php @@ -0,0 +1,44 @@ +dropColumn('comment', 'service_id'); + $this->addColumn('comment', 'entity', $this->string()); + $this->addColumn('comment', 'entity_id', $this->integer()); + } + + /** + * {@inheritdoc} + */ + public function safeDown() + { + echo "m180605_072337_alter_table_comment cannot be reverted.\n"; + + return false; + } + + /* + // Use up()/down() to run migration code without a transaction. + public function up() + { + + } + + public function down() + { + echo "m180605_072337_alter_table_comment cannot be reverted.\n"; + + return false; + } + */ +} diff --git a/console/migrations/m180605_082938_alter_table_article.php b/console/migrations/m180605_082938_alter_table_article.php new file mode 100644 index 0000000..30b6588 --- /dev/null +++ b/console/migrations/m180605_082938_alter_table_article.php @@ -0,0 +1,40 @@ +addColumn('blog_article', 'views', $this->integer()->defaultValue(0)); + } + + /** + * {@inheritdoc} + */ + public function safeDown() + { + $this->dropColumn('blog_article', 'views'); + } + + /* + // Use up()/down() to run migration code without a transaction. + public function up() + { + + } + + public function down() + { + echo "m180605_082938_alter_table_article cannot be reverted.\n"; + + return false; + } + */ +} diff --git a/frontend/config/main.php b/frontend/config/main.php index b02beef..37f78fa 100755 --- a/frontend/config/main.php +++ b/frontend/config/main.php @@ -87,7 +87,8 @@ 'name', 'email', 'comment', - 'service_id' + 'entity_id', + 'entity' ], 'rules' => [ [ @@ -102,7 +103,8 @@ 'name' => 'ФИО', 'email' => 'Email', 'comment' => 'Ваш отзыв', - 'service_id' => false + 'entity_id' => false, + 'entity' => false ], 'inputOptions' => [ diff --git a/frontend/controllers/BlogController.php b/frontend/controllers/BlogController.php index a08c487..63a00fc 100755 --- a/frontend/controllers/BlogController.php +++ b/frontend/controllers/BlogController.php @@ -6,6 +6,8 @@ use common\models\blog\Category; use common\models\blog\Tag; use yii\data\ActiveDataProvider; + use yii\db\ActiveQuery; + use yii\helpers\ArrayHelper; use yii\web\Controller; use yii\web\NotFoundHttpException; @@ -16,16 +18,8 @@ */ class BlogController extends Controller { - public function actionIndex($q = '') + public function actionIndex() { - $tags = Tag::find() - ->with( - [ - 'language', - ] - ) - ->orderBy([ 'sort' => SORT_ASC ]) - ->all(); $categories = Category::find() ->with( @@ -36,7 +30,7 @@ ->where(['status' => true]) ->orderBy([ 'sort' => SORT_ASC ]) ->all(); - + $data = ArrayHelper::map($categories, 'id', 'language.title'); $dataProvider = new ActiveDataProvider( [ 'query' => Article::find() @@ -50,19 +44,14 @@ 'categories.language', ] - ) + )->with(['comments' => function (ActiveQuery $query){ + $query->andWhere(['status' => true]); + }]) ->joinWith('language') ->where([ 'blog_article.status' => true ]) - ->andFilterWhere( - [ - 'ilike', - 'blog_article_lang.title', - $q, - ] - ) ->distinct(), 'pagination' => [ - 'pageSize' => 3, + 'pageSize' => 6, ], ] ); @@ -70,28 +59,29 @@ return $this->render( 'index', [ - 'tags' => $tags, - 'categories' => $categories, + 'categories' => $data, 'dataProvider' => $dataProvider, ] ); } - public function actionView() + public function actionView($id) { -// $model = $this->findModel($id); -// -// $tags = Tag::find() -// ->with([ 'language' ]) -// ->orderBy([ 'sort' => SORT_ASC ]) -// ->all(); -// + $model = $this->findModel($id); + $model->views +=1; + $model->save(); + + $tags = Tag::find() + ->with([ 'language' ]) + ->orderBy([ 'sort' => SORT_ASC ]) + ->all(); + return $this->render( - 'view' -// [ -// 'tags' => $tags, -// 'model' => $model, -// ] + 'view', + [ + 'tags' => $tags, + 'model' => $model, + ] ); } diff --git a/frontend/controllers/SiteController.php b/frontend/controllers/SiteController.php index 423a4c5..5c07822 100755 --- a/frontend/controllers/SiteController.php +++ b/frontend/controllers/SiteController.php @@ -272,7 +272,7 @@ } } $dataProvider = new ActiveDataProvider([ - 'query' => Comment::find()->where(['status' => true])->andFilterWhere(['service_id' => $service_id]), + 'query' => Comment::find()->where(['status' => true])->andWhere(['entity' => Service::className()])->andFilterWhere(['entity_id' => $service_id]), 'pagination' => [ 'pageSize' => 10, ], diff --git a/frontend/views/blog/_article.php b/frontend/views/blog/_article.php index e811949..66387a4 100755 --- a/frontend/views/blog/_article.php +++ b/frontend/views/blog/_article.php @@ -1,7 +1,6 @@ -
-
- -
-

title; ?>

-
- categories)) { ?> -

Без категории

- categories as $category) { - $i++; - ?> -

- title?> - categories)) { - echo ' '; - } else { - echo ', '; - } - ?>

- -

- formatter->asDate($model->created_at); ?> - -

-
-

body_preview; ?>

-

- $model->alias - ], - [ - 'class' => 'btn btn-template-main', - ] - ) ?> -

+
+ + tags)){?> +
+ tags as $tag){?> + title?> + +
+ + diff --git a/frontend/views/blog/index.php b/frontend/views/blog/index.php index 49aed47..faa8b12 100755 --- a/frontend/views/blog/index.php +++ b/frontend/views/blog/index.php @@ -2,8 +2,9 @@ use artbox\core\components\SeoComponent; use yii\data\ActiveDataProvider; - use artbox\core\helpers\Url; + use yii\helpers\Html; use yii\web\View; + use yii\widgets\ActiveForm; use yii\widgets\ListView; /** @@ -49,169 +50,38 @@
-
+
- + 'Все рубрики']+$categories)?>
-
+
- - - - - - - + $dataProvider, + 'itemView' => '_article', + 'options' => [ + 'class' => 'col-xs-12 col-sm-4 col-md-4 blog-list-col', + ], + 'layout' => '{items}{pager}', + ] + ); ?>
diff --git a/frontend/views/blog/view.php b/frontend/views/blog/view.php index 615a27a..e7d80a3 100755 --- a/frontend/views/blog/view.php +++ b/frontend/views/blog/view.php @@ -1,8 +1,8 @@ params[ 'breadcrumbs' ][] = [ -// 'label' => \Yii::t('app', 'Блог'), -// 'url' => [ 'blog/index' ], -// ]; -// -// $this->params[ 'breadcrumbs' ][] = $model->title; + $this->params[ 'breadcrumbs' ][] = [ + 'label' => \Yii::t('app', 'Блог'), + 'url' => [ 'blog/index' ], + ]; + + $this->params[ 'breadcrumbs' ][] = $model->title; + + $moduleComment = \Yii::$app->getModule('comments'); + $moduleComment->inputOptions = array_merge($moduleComment->inputOptions, ['entity_id' => [ + 'type' => 'hiddenInput', + 'options' => ['value' => $model->id], + ], + 'entity' => [ + 'type' => 'hiddenInput', + 'options' => ['value' => Article::className()], + ]]); + + + $moduleComment->buttonTemplate = '
{button}
'; + + $moduleComment->successCallback = 'function (data) { + document.getElementById("comment-form").reset(); + var data = $("#comment-form").data(\'yiiActiveForm\'); + $("#comment-form").find(".submit-close-c-a span").click(); + $("#comment-form").find(".field-comment-comment").parent().after("

Ваш отзыв появиться после проверки модератором

") + data.validated = false; + }' ?> -
-
-
- -
-
-
@@ -39,35 +50,31 @@
-

Диетологи: Финики помогут в борьбе с лишним весом

+

title?>

- + image) ? $model->image->getPath() : null) + ->cropResize(555, 370) + ->quality(84) + ->renderImage()?>
- 20.05.2018 - 246 - 317 + created_at)?> + comments)?> + views?>
- - -

Женщины продолжают интересоваться тем, помогают ли финики бороться с лишним весом, и можно ли их употреблять в большом количестве при диете. Оказывается, что для насыщения организма достаточно съесть несколько плодов.

-

Данный продукт обладает довольно высокой калорийностью, благодаря чему они являются сытными и помогают быстро избавиться от ощущения голода.

-

В некоторых системных диетах финики вводят для снижения веса, как раз на основе этих плодов можно устраивать разгрузочный день. Этим фруктом можно перекусить, ведь преимущество заключается в том, что по итогу не тянет к сладкому, а в составе есть сахароза, которая в виде жира не откладывается, и сразу расходуется организмом.

-

Если применять финиковую диету несколько раз в месяц, это поможет вашему организму избавиться от лишней воды, и восстановит обмен веществ, а также ускорит метаболизм. Растительные волокна плода очищают кишечник от токсинов и шлаков. Диетологи считают нормой около десяти плодов в день, чего будет достаточно для восполнения недостатка полезных веществ.

-


Женщины продолжают интересоваться тем, помогают ли финики бороться с лишним весом, и можно ли их употреблять в большом количестве при диете. Оказывается, что для насыщения организма достаточно съесть несколько плодов.

-

Данный продукт обладает довольно высокой калорийностью, благодаря чему они являются сытными и помогают быстро избавиться от ощущения голода.

-

В некоторых системных диетах финики вводят для снижения веса, как раз на основе этих плодов можно устраивать разгрузочный день. Этим фруктом можно перекусить, ведь преимущество заключается в том, что по итогу не тянет к сладкому, а в составе есть сахароза, которая в виде жира не откладывается, и сразу расходуется организмом.

-

Если применять финиковую диету несколько раз в месяц, это поможет вашему организму избавиться от лишней воды, и восстановит обмен веществ, а также ускорит метаболизм. Растительные волокна плода очищают кишечник от токсинов и шлаков. Диетологи считают нормой около десяти плодов в день, чего будет достаточно для восполнения недостатка полезных веществ.

+ body?> + tags)){?> +
@@ -78,54 +85,30 @@
+
+
Отзывы
+ comments)){?>
+ comments as $comment){?>
-
Мария
-
Спасибо за профессиональное и качественное лечение. Медсестрам за проведенные процедуры. Результатом лечения довольна.
-
20.05.2018
-
- -
-
Наталья
-
Спасибо за профессиональное и качественное лечение. Медсестрам за проведенные процедуры. Результатом лечения довольна.
-
20.05.2018
-
- -
-
Татьяна
-
Спасибо за профессиональное и качественное лечение. Медсестрам за проведенные процедуры. Результатом лечения довольна.
-
20.05.2018
+
name?>
+
comment?>
+
created_at)?>
+
- + +
+
Оставить отзыв
-
-
- - -
- -
- - -
- -
- - -
- -
- -
-
+ renderForm($this)?>
diff --git a/frontend/views/service/view.php b/frontend/views/service/view.php index 2d288bc..fe4c5d3 100644 --- a/frontend/views/service/view.php +++ b/frontend/views/service/view.php @@ -17,10 +17,14 @@ $moduleComment = \Yii::$app->getModule('comments'); $this->params[ 'breadcrumbs' ][] = (!empty($seo->h1)) ? $seo->h1 :$model->title; - $moduleComment->inputOptions += ['service_id' => [ + $moduleComment->inputOptions = array_merge($moduleComment->inputOptions, ['entity_id' => [ 'type' => 'hiddenInput', 'options' => ['value' => $model->id], - ]]; + ], + 'entity' => [ + 'type' => 'hiddenInput', + 'options' => ['value' => Service::className()], + ]]); $moduleQuestion = \Yii::$app->getModule('questions'); $moduleQuestion->inputOptions += ['service_id' => [ @@ -43,7 +47,7 @@
  • title?>
  • - + diff --git a/frontend/views/site/comments.php b/frontend/views/site/comments.php index 493239a..f5b2833 100644 --- a/frontend/views/site/comments.php +++ b/frontend/views/site/comments.php @@ -8,7 +8,7 @@ use artbox\core\helpers\Url; use common\models\Comment; - use common\models\Question; + use common\models\Service; use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\widgets\ActiveForm; @@ -16,7 +16,7 @@ $this->params[ 'breadcrumbs'][] = \Yii::t('app', 'Вопрос-ответ'); - $model = new Comment(['service_id' => $service_id]); + $model = new Comment(['entity_id' => $service_id, 'entity' => Service::className()]); $data = ['' => 'Общие вопросы'] + ArrayHelper::map($services, 'id', 'title'); ?> @@ -39,7 +39,7 @@ 'total_comment_form'])?>
    - field($model, 'service_id')->dropDownList($data)->label('Выбор отделения')?> + field($model, 'entity_id')->dropDownList($data)->label('Выбор отделения')?>
    -- libgit2 0.21.4