H
H
hobu4ok912016-04-07 03:15:39
Yii
hobu4ok91, 2016-04-07 03:15:39

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

4 answer(s)
M
Maxim Timofeev, 2016-04-07
@hobu4ok91

<?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(); ?>

In the controller
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;
}

I think the idea is clear.

J
justyork, 2016-04-07
@justyork

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

X
xmoonlight, 2016-04-07
@xmoonlight

https://github.com/Chiliec/yii2-vote

H
hobu4ok91, 2016-04-07
@hobu4ok91

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 question

Ask a Question

731 491 924 answers to any question