Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 30 ยท Projects

Project: Wishlist Lite Module

Build a small PrestaShop wishlist module: a table, an ajax front controller, customer context, a product page button and a clean uninstall, with runnable SQLite stand-ins.

A wishlist is a good first "real" module. It needs almost every skill from this track in a small space: a database table, a front controller that answers ajax calls, the logged-in customer from the context, a button added to the product page through a hook, and an uninstall that leaves nothing behind. It also forces you to think about security, because anyone can send a request to a public URL.

This project builds wishlistlite: a heart button on the product page that adds or removes the product from the current customer's list. PrestaShop cannot run on this site, so the real PHP, Smarty and JavaScript below are read-only. After each part you get a runnable plain-PHP stand-in (SQLite instead of MySQL, a tiny router instead of the PrestaShop front controller). The stand-ins are not PrestaShop code; they show the same logic with the same rules.

What you will build

flowchart LR
    P["Product page"] --> H["Hook<br/>displayProductAdditionalInfo"]
    H --> B["Heart button"]
    B -->|"fetch POST + token"| C["Front controller<br/>toggle"]
    C --> X{"Logged in<br/>and token valid?"}
    X -->|"no"| E["401 or 403 JSON"]
    X -->|"yes"| D[("Table<br/>wishlistlite_item")]
    D --> R["JSON: saved or removed"]

The page only renders a button. All writes go through one guarded controller action.

The module folder:

TEXT
modules/wishlistlite/
  wishlistlite.php
  config.xml            (generated by PrestaShop on first load)
  logo.png
  index.php
  controllers/front/toggle.php
  views/templates/hook/button.tpl
  views/js/wishlistlite.js

Step 1: the table and the installer

One row means "this customer saved this product". A unique key on the pair makes a duplicate impossible, even if two requests arrive at the same moment. The module class creates the table in install() and drops it in uninstall().

PHP
<?php
if (!defined('_PS_VERSION_')) {
    exit;
}

class WishlistLite extends Module
{
    public function __construct()
    {
        $this->name = 'wishlistlite';
        $this->tab = 'front_office_features';
        $this->version = '1.0.0';
        $this->author = 'Acme';
        $this->need_instance = 0;
        $this->ps_versions_compliance = ['min' => '8.0.0', 'max' => _PS_VERSION_];
        parent::__construct();

        $this->displayName = $this->trans('Wishlist Lite', [], 'Modules.Wishlistlite.Admin');
        $this->description = $this->trans('Let customers save products.', [], 'Modules.Wishlistlite.Admin');
    }

    public function install(): bool
    {
        return parent::install()
            && $this->installDb()
            && $this->registerHook('displayProductAdditionalInfo')
            && $this->registerHook('actionFrontControllerSetMedia');
    }

    public function uninstall(): bool
    {
        return $this->uninstallDb() && parent::uninstall();
    }

    private function installDb(): bool
    {
        return Db::getInstance()->execute(
            'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'wishlistlite_item` (
                `id_item` INT UNSIGNED NOT NULL AUTO_INCREMENT,
                `id_customer` INT UNSIGNED NOT NULL,
                `id_product` INT UNSIGNED NOT NULL,
                `date_add` DATETIME NOT NULL,
                PRIMARY KEY (`id_item`),
                UNIQUE KEY `customer_product` (`id_customer`, `id_product`)
            ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8mb4'
        );
    }

    private function uninstallDb(): bool
    {
        return Db::getInstance()->execute('DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'wishlistlite_item`');
    }
}

The prefix _DB_PREFIX_ and the engine _MYSQL_ENGINE_ come from the shop's configuration. See Tables, Installers and Upgrades for the full pattern, including upgrade files. This project stores plain customer and product ids and no ObjectModel; for a bigger module you would model the row as an ObjectModel.

A stand-in for the table

The first stand-in is a small repository on SQLite. It has the same unique key, so a second "add" of the same product does nothing instead of creating a duplicate.

PHP Wishlist table with a unique key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last two lines are only a reminder that uninstall means gone: DROP TABLE removes the data too, so a real module often asks the merchant before deleting customer data, or offers a setting for it.

Step 2: the front controller

The button needs a URL to call. A module front controller lives in controllers/front/ and its class name is the module name, the controller name and ModuleFrontController joined together. The file toggle.php therefore holds WishlistLiteToggleModuleFrontController. Its public URL comes from $link->getModuleLink('wishlistlite', 'toggle', [], true).

PHP
<?php
class WishlistLiteToggleModuleFrontController extends ModuleFrontController
{
    public function postProcess(): void
    {
        header('Content-Type: application/json');

        if (!$this->context->customer->isLogged()) {
            http_response_code(401);
            $this->ajaxRender(json_encode(['error' => 'login_required']));
            return;
        }

        $token = (string) Tools::getValue('token');
        if (!hash_equals(Tools::getToken(false), $token)) {
            http_response_code(403);
            $this->ajaxRender(json_encode(['error' => 'bad_token']));
            return;
        }

        $customerId = (int) $this->context->customer->id;
        $productId = (int) Tools::getValue('id_product');

        if ($productId < 1 || !Product::existsInDatabase($productId, 'product')) {
            http_response_code(404);
            $this->ajaxRender(json_encode(['error' => 'unknown_product']));
            return;
        }

        $db = Db::getInstance();
        $table = 'wishlistlite_item';
        $where = 'id_customer = ' . $customerId . ' AND id_product = ' . $productId;

        if ($db->getValue('SELECT 1 FROM `' . _DB_PREFIX_ . $table . '` WHERE ' . $where)) {
            $db->delete($table, $where);
            $state = 'removed';
        } else {
            $db->insert($table, [
                'id_customer' => $customerId,
                'id_product' => $productId,
                'date_add' => date('Y-m-d H:i:s'),
            ], false, true, Db::INSERT_IGNORE);
            $state = 'saved';
        }

        $this->ajaxRender(json_encode(['state' => $state]));
    }
}

Read the order of the checks, because it matters:

  1. Who is asking? The customer comes from the context, never from a request parameter. If the browser could send id_customer, anyone could edit anyone's list.
  2. Is this request intended? The static token from Tools::getToken(false) is the CSRF protection described in Security in Modules. hash_equals compares in constant time.
  3. Is the input sane? The product id is cast to an integer and checked to exist. Integer casts are also what make the SQL string safe here, because only numbers are concatenated.
  4. Only then write.

Check in your PrestaShop version how ajaxRender behaves (it prints the value and does not stop the script by itself in recent versions) and whether Product::existsInDatabase fits your needs. The structure, not the exact helper, is what carries over.

A stand-in for the controller

The second stand-in is a miniature request handler with the same checks in the same order. A "session" array plays the role of the context, and a fixed secret plays the role of the token.

PHP Guarded toggle action with JSON answers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The guest, the wrong token and the unknown product are all stopped before the database is touched. The same button click saves on the first press and removes on the second, which is why the action is called a toggle.

Step 3: the button on the product page

Two hooks do the front-office work. displayProductAdditionalInfo returns HTML for the product page, and actionFrontControllerSetMedia registers the JavaScript file and passes the URL and state to it. Both methods go in the module class.

PHP
public function hookDisplayProductAdditionalInfo(array $params): string
{
    $product = $params['product'];

    $this->context->smarty->assign([
        'wishlistlite_product_id' => (int) $product['id_product'],
        'wishlistlite_logged' => $this->context->customer->isLogged(),
        'wishlistlite_login_url' => $this->context->link->getPageLink('authentication'),
    ]);

    return $this->display(__FILE__, 'views/templates/hook/button.tpl');
}

public function hookActionFrontControllerSetMedia(): void
{
    if ($this->context->controller->php_self !== 'product') {
        return;
    }

    $this->context->controller->registerJavascript(
        'module-wishlistlite',
        'modules/' . $this->name . '/views/js/wishlistlite.js',
        ['position' => 'bottom', 'priority' => 200]
    );

    Media::addJsDef([
        'wishlistLite' => [
            'url' => $this->context->link->getModuleLink($this->name, 'toggle', [], true),
            'token' => Tools::getToken(false),
        ],
    ]);
}

The template stays tiny. Output goes through Smarty's escaping, and the customer-specific state is not baked into the HTML, because product pages may be cached by a CDN or full-page cache. The button always renders in the same way and the script asks the server only when clicked.

SMARTY
{if $wishlistlite_logged}
  <button type="button" class="btn btn-link js-wishlist-toggle"
          data-id-product="{$wishlistlite_product_id|intval}">
    {l s='Save to wishlist' d='Modules.Wishlistlite.Shop'}
  </button>
{else}
  <a href="{$wishlistlite_login_url|escape:'html':'UTF-8'}">
    {l s='Log in to save this product' d='Modules.Wishlistlite.Shop'}
  </a>
{/if}
JavaScript
document.addEventListener('click', async (event) => {
  const button = event.target.closest('.js-wishlist-toggle');
  if (!button) return;

  const body = new FormData();
  body.append('id_product', button.dataset.idProduct);
  body.append('token', wishlistLite.token);

  const response = await fetch(wishlistLite.url, { method: 'POST', body, credentials: 'same-origin' });
  const data = await response.json();
  button.textContent = data.state === 'saved' ? 'Saved' : 'Save to wishlist';
});

Because the logged-in check is in the template, a guest-cached page would show the wrong variant to some visitors. If your shop caches product pages for everyone, render both variants and let a small script choose, or call a controller for the state, the same idea this site uses for progress on its own pages.

Step 4: uninstall and what to keep

uninstall() already drops the table. Also remember to remove anything else the module created: configuration keys (Configuration::deleteByName), custom hooks, tabs and uploaded files. After uninstalling, test that the shop works without the module, and that installing it again works from a clean state. A module that cannot be reinstalled is a common source of support tickets. See Overrides vs Hooks for why this module uses hooks only, which is what makes its removal safe.

Ideas for extending it

  • A "My wishlist" page: a second front controller that lists products with their names, using the context language.
  • A counter in the header, updated from the toggle response.
  • An action hook when something is saved, so other modules can react: see custom hooks.
  • Tests for the repository logic away from the core, as described in Testing Modules.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the toggle action read the customer from the context instead of from a request parameter?

    The server knows who is logged in. A value sent by the browser can be forged, so identity must never come from it.
  2. 2. What does the unique key on (id_customer, id_product) protect against?

    The database enforces the rule itself, so the check does not depend on application code winning a race.
  3. 3. Why is the customer-specific state not rendered into the product page HTML?

    Cached pages must look the same for everyone. User-specific state is loaded or changed by a separate request.
  4. 4. What should uninstall() do in this module?

    Uninstall must clean up what install created, so the shop works without the module and a later reinstall starts clean.

Summary

  • The project combines a table with a unique key, a guarded front controller, two hooks, a small template and a script.
  • Check in order: who is asking (context), is it intended (token), is the input valid, then write.
  • Never trust ids from the browser for identity; cast and verify product ids.
  • Keep cached HTML identical for everyone and ask the server for user-specific state.
  • Uninstall removes the table and every other trace, and a reinstall must work.

Next, a back office project that exports data to a file: Project: Order Export to CSV.