Follow me and receive all the latest free scripts:

By Email:

Most Popular Posts

Symfony2 Star Rating System

Symfony2 Star Rating System

Published January 16, 2016 by , category Symfony 2

Symfony2AJAXjQueryStar Rating SystemStar Rating

Symfony2 Star Rating System using jQuery and AJAX


In this tutorial I will show you how to implement a star rating system in your Symfony2 web application.

This tutorial IS NOT about how to install and use Symfony2 framework. I consider you already know all the basic things and how to develop a website with Symfony2 step by step. I consider you know each of the major component pieces: Controllers, Routing, Doctrine, Forms...
If not, I would advice you to look through the official documentation. It will give you a better understanding of how the Symfony framework works.

Installing jQuery

With Symfony2 framework, you can work with any JavaScript library, so we will use a JavaScript framework, jQuery.

Simply include a link to jQuery framework somewhere in your layout:

<script type="text/javascript" src=""></script>

Or (if you host jQuery yourself):

<script src="{{ asset('bundles/tuto/js/jquery-1.10.1.min.js') }}"></script>

Live demo

Please visit the Symfony2 Ajax Lab to see a working demo.

Database structure sample

For this tutorial, I use two tables:

  1. An items table called s2_tuto_items with two fields: id, a standard auto increment field and name, a varchar field. Just insert some items inside. You may want to add more fields. No problem, just adapt the Symfony entities (All the code is in the demo page).
  2. An rating table called s2_tuto_rating where rates will go, with four fields: id, a standard auto increment field, media, an integer field which is the item Id, rate, also an integer field, this is the total rate value and nbrrate, another integer field, the total of votes.
CREATE TABLE IF NOT EXISTS `s2_tuto_items` (
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)

CREATE TABLE IF NOT EXISTS `s2_tuto_rating` (
  `media` int(11) NOT NULL,
  `rate` int(3) NOT NULL,
  `nbrrate` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_2` (`id`),
  KEY `id` (`id`)

Symfony2, create tables from entities

Symfony2 offers you the possibility to create tables from entities. In the demo page, I provide you all the code, including the entities items.php and starratingsystem.php. So you may simply use doctrine command:
php app/console doctrine:database:create.


Please go to the demo page to get the full code, bundle name and structure, plus explanations.

For all the next Symfony2 tutorials the bundle name will be Sim100/TutoBundle.


Don't forget to adapt the code. I mean replace the Symfony2 namespace and uses if you don't use the same bundle name!

I hope you enjoy this tutorial. If you have questions, please post below.

About Simon Laroche
Simon Laroche on Google+
Simon Laroche on Twitter
Simon Laroche on Facebook
Simon Laroche on Pinterest
Simon Laroche on LinkedIn
: I am a Coder, Designer, Webmaster and Expert SEO Consulting, I'm also a wise traveller and an avid amateur photographer. I created the website TipoCode and many others such as Landolia: a World of Photos...

If you need help about this script, please leave a comment below. I reply as much as I can depending of my time, you may also get help from others.
I also offer a paid support, if you are in the need to adapt or create a script...

Leave a comment

Comments (16 comments)

Amira Bedhiafi Posted on April 12, 2018
I'm asking about the repositories code for each entity.It was in the annotation in the entities but couldn't find the code.Thank you. Posted on April 09, 2017
i have a problem on $query = $this->doctrine->getRepository('Sim100TutoBundle:starratingsystem')->findOneBy(array('media'=>$mediaId));

Method "findOneBy" not found
zadim Posted on November 29, 2016
en executant le code ,j'ai ce code d'erreur
The autoloader expected class "Sim100\TutoBundle\Repository\itemsRepository" to be defined in file "C:\wamp64\www\TestStarRating\vendor\composer/../../src\Sim100\TutoBundle\Repository\itemsRepository.php". The file was found but the class was not in it, the class name or namespace probably has a typo.
500 Internal Server Error - RuntimeException
murat Posted on November 06, 2016
Hello. thank you for this article. How can we integrate this product to laravel ? Thank you in advance.
Sirius Posted on October 30, 2016
Hi, Thanks for this tutorial. I having a problem when I click on the star nothing happens, the vote is note saved in the database. I have added manually some data in the database and in the view the number of vote is display and also the rate on the star. I'm using symfony 2.8.

This is how look my configuration:

Routing.yml and service.yml




I have also added the following libraries:

<script src=""></script>
<script src=""></script>

Simon Laroche
Simon Laroche Posted on September 21, 2016
@laurent : je regarde vite fait et je ne vois pas aussi, cela marche sans le $getJSON ?
Car les arguments sont passés par la fonction rateMedia et l'attribut rel n'est récupérée nul part...
Je n'ai pas le temps de tester de suite mais je regarderais et l'enlèverais si nécessaire. Il se peut que j'ai laissé un bout de code traîner inutilement suite à des modifications...
laurent Posted on September 21, 2016

Je ne comprends pas à quoi te sert la création du Json que tu injectes dans la balise : rel='.$getJSON.'> du fichier starBarExtension.php

$getJSON = array('numStar' => $numStar, 'mediaId' => $mediaId); // We create a JSON with the number of stars and the media ID

$getJSON = json_encode($getJSON);

A part ce point, le code a été adapté pour SF3 et MongoDB et cela fonctionne très bien.
Laurent Posted on September 16, 2016
Bonjour, merci (c'est quand même plus facile en français - lol).
J'ai trouvé ce matin la bonne séquence d'échappement .

$starBar .= ' onmouseover="overStar(\'' .$articleId. '\', '.$i.', '.$numStar.');" onmouseout="outStar(\''.$articleId.'\', '.$i.', '.$numStar.');" onclick="rateMedia(\''.$articleId.'\', '.$i.', '.$numStar.', '.$starWidth.');"';

Il faut ajouter :
\ ' ' => antislash + simple cote + simple cote devant .$articleId 

'\' => simple cote + antislash + simple cote

Pour la base de données, j'utilise MongoDB. Je n'ai pas de notion de varchar, mais ce n'est pas un problème.

J'attaque ce soir la partie ajax, j'ai vu quelques erreurs.

Simon Laroche
Simon Laroche Posted on September 16, 2016
@Laurent: votre chaîne "57cf2272d10053076cadb765" est un varchar (lettre et chiffre) donc cela ne peut pas marcher.
Quelques pistes :
Déjà il faudra l'entourer de guillemets
outStar("57cf2272d10053076cadb765", 4, 5);

Idem dans le passage de la variable un peut partout et dans le javascript
Pour un chiffre c'est :
myvar = 5;

Pour une chaîne de caractère :
myvar = "texte et chiffres";

Et aussi changer les INT par des VARCHAR dans la base de données bien évidemment.
Et puis dans les ENTITES de Symfony il faut aussi déclarer des VARCHAR.

Enfin c'est pas mal de petits changement mais pas compliqués.
Laurent Posted on September 15, 2016

j'ai une erreur javascript sur les événement onclik, onmouseover... :

outStar(57cf2272d10053076cadb765, 4, 5);

Le code est le suivant : onmouseover="overStar('.$articleId.'..... à priori le caractère d'échappement ne fonctionne pas et d'après ce que j'ai compris, il n'est pas possible de démarrer avec un numérique.

Bon bref je cale.

Simon Laroche
Simon Laroche Posted on September 13, 2016
@laurent : thank you for sharing. I am sure it will help others users.
laurent Posted on September 12, 2016
Hi, i find a solution for Symfony3 and mongoDB.
Just in the service :

class: PortailBundle\Twig\StarBarExtension
public: false
arguments: [ "@doctrine.odm.mongodb.document_manager", "@request_stack" ]
name: twig.extension

And in the class :

First :
namespace PortailBundle\Twig;
use Symfony\Component\HttpFoundation\RequestStack;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Component\HttpFoundation\Cookie;

Second :
public function __construct(DocumentManager $doctrine, RequestStack $RequestStack)
$this->doctrine_mongodb = $doctrine;
$this->requestStack = $RequestStack;

And finaly :
$cookies = $this->requestStack->getCurrentRequest()->cookies->get('LilmodLemaedNote'.$mediaId);

$nbrPixelsInDiv = $numStar * $starWidth; // Calculate the DIV width in pixel

$query = $this->doctrine_mongodb->getRepository('PortailBundle:Notes')->findOneBy(array('ARTICLE' =>$mediaId));

Simon Laroche
Simon Laroche Posted on September 09, 2016
@laurent: no I don't know, sorry. Should be easy, just have to search. Maybe some day I dl Symfony3 and adapt the script...
laurent Posted on September 09, 2016
Hi, i am migrate the code to Symfony3. it is ok but i Have a problem with the service declaration. I use MongoDB and not mysql. I don't know how to adapt the service declaration ("@doctrine"] and how to get the contenair in the class.
Have you any idea ?
laurent Posted on September 08, 2016
Thanks for this beautiful tuto.
I am integrating the code in my application under Symfony 3.
Could you post an archive of your bundle please, it will be fine to get the structure to adapt in our context.
Murat Posted on July 16, 2016
Hello. thank you for this article. How can we integrate this product to laravel ? Thank you in advance.