Answer the question
In order to leave comments, you need to log in
How to organize a post rating system +1 -1?
How to organize a post rating system +1 -1, with rating storage in the database, with voting without reloading the page (this is my main problem). And all this needs to be done in the Yii2 framework.
Answer the question
In order to leave comments, you need to log in
<?php \yii\widgets\Pjax::begin(); ?>
<span>Рейтинг 256</span>
<a href="/vote?id=айдизаписи&plus=true">+</a>
<a href="/vote?id=айдизаписи&plus=false">+</a>
<?php \yii\widgets\Pjax::end(); ?>
public function actionVote($id,$plus){
$x=1
if($plus)
$x = -1;
$model = Chtoto::findOne($id);
$model->rating = $model->rating + $x;
if($model->save())
return $this->renderAjax('_вьюшка_Блока_рейтинга_и_кнопок',['rating'=>$model->rating]);
return false;
}
you make an ajax request when you click on the +1 or -1 button, which will be edited in your base post, putting down the desired rating for it. Something like this
Created 2 actions in the controller:
public function actionVoteUp($id)
{
$post = Post::findOne($id);
if (!$post->ratingUsers) {
$post->updateCounters(['rating' => 1]);
$model = new RatingUser();
$model->user_id = Yii::$app->user->id;
$model->post_id = $id;
$model->save();
} else {
Yii::$app->session->setFlash('error', 'You have already voted for this post');
}
return $this->renderAjax('vote', ['post' => $post]);
if (!$post->ratingUsers) {
$post->updateCounters(['rating' => -1]);
$model = new RatingUser();
$model->user_id = Yii::$app->user->id;
$model->post_id = $id;
$model->save();
} else {
Yii::$app->session->setFlash('error', 'You have already voted for this post');
}
return $this->renderAjax('vote', ['post' => $post]);
}
View: <?php \yii\widgets\Pjax::begin(['enablePushState' => false]); ?>
<?= $post->rating ?>
<?= Yii::$app->session->getFlash('error')?>
< ?php \yii\widgets\Pjax::end(); ?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question