Adding the Compare button to the Product page

In this tutorial, we will see how easy it is to add the compare button to the product page, by only adding a couple of lines to the tpl and using a lightweight override

  • Version used: Prestashop 1.5.4.1

Understanding how the “Compare” feature works

First of all, we need to understand how the compare feature works. Whenever you click on a checkbox to add a product to the comparison table, Prestashop triggers a javascript event, declared in the reloadProductComparison function of the file products-comparison.js. This file, by default, is added to every page where a product list is displayed. Thus, in addition to the simple blocks of html necessary to display the compare button, we need to consider this as well. We will do it by adding that Javascript file to the header from the setMedia method of the Product Controller.

Additionally, Every time an item is added or removed from the comparison table, and ajax function, which updates the current “compare list”, is called, and this very same list is saved into a cookie variable. Prestashop needs to know which items are already in the table, how many they are, and if it is possible to compare products (if the maximum products comparison number is more than 0). Thus, we also need to add a couple of variables to the already mentioned ProductController.php, and nothing will better suit the case than an override.

Therefore, our plan of action is:

  • Creating the ProductController.php override
  • Adding products-comparison.js to the setMedia() method of this new Controller
  • Extending the initContent method to account for the comparison variables
  • Embedding the necessary code inside product.tpl

 

No fear, it’s easier and quicker than it seems. Let’s get started!

Overriding ProductController.php

As always, if you’re not used to Prestashop Overrides, have a look at the basic Prestashop documentation the Prestateam wrote for us, or my own tutorial on How to extend Prestashop Objects.

Create a new .php file inside override/controllers/front and call it ProductController. Write the following snippet inside

<?php

class ProductController extends ProductControllerCore
{
}
?>

Then, let’s start by embedding products-comparison.js. Override the setMedia() method as follows

	public function setMedia()
	{
		parent::setMedia();

		if (Configuration::get('PS_COMPARATOR_MAX_ITEM'))
			$this->addJS(_THEME_JS_DIR_.'products-comparison.js');
	}

Remember to call parent::setMedia() so that all needed javascript and css files are included! WHat we are doing here is really straightforward: if the maximum allowed number of products for the comparison feature is more than zero, then include that Javascript file.

Then, let’s extend initContent() as well:

	public function initContent()
	{

		$this->context->smarty->assign('comparator_max_item', Configuration::get('PS_COMPARATOR_MAX_ITEM'));
		
		if (isset($this->context->cookie->id_compare))
			$this->context->smarty->assign('compareProducts', CompareProduct::getCompareProducts((int)$this->context->cookie->id_compare));

		parent::initContent();
	}	

First, we assign that same comparator item number to the template. Then, if the user added products to the comparison table (so if it has a cookie with product data saved), we assign the list of the added products IDS the template. Of course, we also call the original initContent() at the end of the overridden method.

Adding the Compare button and checkbox to the Product page

So far, so good. Just to be sure our last changes didn’t break anything, go to the cache/ folder and delete class_index.php. Refresh the product page and see if any error pops out. If not, read on!

Open up product.tpl and locate a suitable place for the compare button. I chose to add it right above the buy block at about line 264 of the default template. We can re-use the code from category.tpl and product-list.tpl, with some slight modification. Add the following snippet to the template:

		
		{if isset($comparator_max_item) && $comparator_max_item}
			<p class="compare">
				<input type="checkbox" class="comparator" id="comparator_item_{$product->id}" value="comparator_item_{$product->id}" {if isset($compareProducts) && in_array($product->id, $compareProducts)}checked="checked"{/if} /> 
				<label for="comparator_item_{$product->id}">{l s='Select to compare'}</label>
			</p>
		{/if}
		{include file="./product-compare.tpl"}

Notice that we are using $product->id instead of $product.id_product to refer to the product id.

Save & refresh. Done!!

The Prestashop Compare button in a single product page 

You like the tuts and want to say "thank you"? Well, you can always feel free to donate:

  • Juan Pablo Mty

    Hola una pregunta.
    No entiendo bien donde van cada uno de los códigos, los he puesto en el fichero llamado ProductController.php

    todo dentro de los { } del primer código que adjuntas

    También añado el código al product.tpl aparece el botón y redirige a la página de comparación pero no añade el producto seleccionado.

  • Илья Китаев

    Thanks, Dude! Especially for ‘Notice that we are using $product->id’!

  • NemoPS

    Hi there! What’s your prestashop version?

  • alex

    is it work fine on prestashop 1.6 +?

    greetings,

    alex

  • Thomas Hastir

    Hi! Any idea to make it works on 1.6?

Store Top Sales

You like the tuts and want to say "thank you"? Well, you can always feel free to donate: