I implemented a vote system for my users on a forumbundle. It works fine but I would like to restrinct and just let vote 1 time for user. So I create a Boolean voted on my bdd. But I don't know how should I can avoid that user's can vote again but at the same time I'd like to let them undo the vote.
So I made this function :
public function ScoreAction(Request $request){
$em = $this->getDoctrine()->getManager();
$idTopic = $request->request->get('id_topic');
$idPoster = $request->request->get('id_poster');
$positive= $request->request->get('positive');
$negative= $request->request->get('negatiu');
$user= $em->getRepository(User::class)->findOneById($idPoster);
$topic = $em->getRepository(Topic::class)->findOneById($idTopic);
$score= $user->getReputation();
$voted = $user->getVoted();
if ($positive!= null) {
$score= $score+ 1;
$voted = 1;
}
if($negative!= null){
$score= $score- 1;
$voted = 1;
}
$user->setReputation($score);
$user->setVoted($voted);
$em->persist($user);
$em->flush();
$redirect = $this->generateUrl('discutea_forum_post', array('slug' => $topic->getSlug()));
return $this->redirect($redirect);
}
Update with change boolean for int nullable on my Database and made this code:
$score = $user->getReputation();
$voted = $user->getVoted();
if ($voted == null) {
if ($positive != null) {
$score = $score + 1;
$voted = 1;
}
if($negative != null){
$score = $score - 1;
$voted = 0;
}
}else if($voted == 1){
if ($negative != null) {
$score = $score - 1;
$voted = 0;
}
}else if($voted == 0){
if ($positive != null) {
$score = $score + 1;
$voted = 1;
}
}
$user->setReputation($score);
$em->persist($user);
$em->flush();
$voted = $user->getVoted();
if ($voted) {
//just redirect somewhere else, without making an actual vote
} else {
//do your vote stuff
//persist and flush etc
//redirect somewhere else
}
something along those lines ?
are you trying to achieve the following ?:
$voted = $user->getVoted();
if ($voted) {
if ($positive!= null) {
$user->setReputation($user->setReputation()+2);
}
if ($negative!= null){
$user->setReputation($user->setReputation()-2);
}
} else {
if ($positive!= null) {
$user->setReputation($user->setReputation()+1);
}
if ($negative!= null){
$user->setReputation($user->setReputation()-1);
}
}
EDIT:
try this
if ($voted === null) {
if ($positive != null) {
$score = $score + 1;
}
if($negative != null){
$score = $score - 1;
}
}else if($voted === 1){
if ($negative != null) {
$score = $score - 1;
}
}else if($voted === 0){
if ($positive != null) {
$score = $score + 1;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.