LogoLogo
Homepage
  • Documentations for PrestaShop 1.5
  • English documentation 1.5
    • About PrestaShop 1.5
    • New features in PrestaShop 1.5
    • Getting Started
      • What you need to get started
      • Installing PrestaShop
      • Installing PrestaShop using the command line
      • Updating & Uninstalling
      • Misc. information
    • Updating PrestaShop
      • Automatic update
      • Manual update
      • Making and restoring your own backup
      • In case of issues
    • User Guide
      • Training
      • Customizing your shop
      • Browsing the front-office
      • Connecting to the PrestaShop back-office
      • First steps with PrestaShop 1.5
      • Adding Products and Product Categories
      • A Look Inside the Catalog
      • Managing Orders
      • Managing Customers
      • Creating Price Rules and Vouchers
      • Managing Shipping
      • Understanding Local Settings
      • Managing Modules and Themes
      • Making the Native Modules Work
      • Understanding the Preferences
      • Understanding the Advanced Parameters
      • Administering the Back-Office
      • Understanding Statistics
      • Advanced Stock Management
      • Managing Multiple Shops
    • Developer Guide
      • Developer tutorials
        • Using the PrestaShop Web Service
          • Webservice one-page documentation
          • Chapter 1 - Creating Access to Back Office
          • Chapter 2 - Discovery - Testing access to the web service with the browser
          • Chapter 3 - First steps - Access the Web service and list client
          • Chapter 4 - Retrieve Data - Retrieving a Client
          • Chapter 5 - Modification - Update client
          • Chapter 6 - Creation - Remote Online Form
          • Chapter 7 - Removal - Remove customer accounts from the database
          • Chapter 8 - Advanced Use
          • Chapter 9 - Image management
          • Chapter 10 - Price management
          • Cheat-sheet - Concepts outlined in this tutorial
          • Web service reference
        • Helpers
          • HelperForm
          • HelperOptions
          • HelperList
          • Using helpers to overload a back-office template
        • New Developers Features In PrestaShop 1.5
        • Using the Context Object
        • DB class best practices
        • Public and overloadable methods
        • Overriding default behaviors
        • Using addJquery(), addJqueryPlugin() and addJqueryUI()
        • Handling special characters in links
        • Auto-updating modules
        • Front-Office Controllers
        • Controllers correspondence table
        • Specifics of multistore module development
        • Developer tips and tricks
        • PrestaShop's developer tools
        • Using the backward compatibility toolkit
      • Fundamentals
      • Coding Standards
      • Setting up your local development environment
      • Diving into PrestaShop Core development
      • Creating a PrestaShop module
      • Creating a front-office module
      • Creating a module with both front-end and back-end controllers
      • Hooks in PrestaShop 1.5
      • Translations in PrestaShop 1.5
      • How to use the Forge to contribute to PrestaShop
      • How to write a commit message
      • Contributing code to PrestaShop
    • Designer Guide
      • Theme development fundamentals
      • Integrating content in a page using hooks
      • Characteristics of a front-office theme
      • Characteristics of a back-office theme
      • Creating your own theme
      • Theme templates and Smarty
      • Using jQuery and Ajax
      • Best practices
      • Designer tutorials
        • Changes in version 1.5 which impact theme development
        • Changing a 1.4 theme to support gift products
        • Implementing layered navigation in a theme
    • System Administrator Guide
    • Merchant's Guide
      • Our advices
      • Sample price rules
    • FAQ
      • Using PrestaShop with WordPress
    • Troubleshooting
  • Documentation française 1.5
    • À propos de PrestaShop 1.5
    • Nouveautés de PrestaShop 1.5
    • Guide de démarrage
      • Ce dont vous avez besoin
      • Installer PrestaShop
      • Installer PrestaShop en ligne de commande
      • Mettre PrestaShop à jour
      • Informations diverses
    • Guide de mise à jour
      • Mise à jour automatique
      • Mise à jour manuelle
      • Faire une sauvegarde et la restaurer
      • En cas de problème
    • Guide de l'utilisateur
      • Formations
      • Personnaliser votre boutique
      • Parcourir le front-office
      • Se connecter au back-office de Prestashop
      • Premiers pas avec PrestaShop 1.5
      • Ajouter des produits et des catégories de produits
      • Un aperçu du catalogue
      • Gérer les commandes
      • Gérer les clients
      • Mettre en place des promotions
      • Gérer les transporteurs
      • Comprendre les réglages locaux
      • Gérer les modules et les thèmes
      • Configurer les modules natifs
      • Comprendre les préférences
      • Comprendre les paramètres avancés
      • Administrer le back-office
      • Comprendre les statistiques
      • Gestion avancée des stocks
      • Gérer plusieurs boutiques
    • Guide du développeur
      • Fondamentaux
      • Norme de développement
      • Mettre en place votre environnement de développement
      • Plonger dans le développement PrestaShop
      • Créer un module PrestaShop
      • Les hooks de PrestaShop 1.5
      • Les traductions dans PrestaShop 1.5
      • Comment utiliser la Forge pour contribuer à PrestaShop
      • Comment écrire un descriptif de modification
    • Guide de l'intégrateur
      • Fondamentaux de la création de thème
      • Intégrer du contenu dans une page à l'aide de hooks
      • Caractéristiques d'un thème front-office
      • Caractéristiques d'un thème back-office
      • Template de thème et Smarty
      • Utiliser jQuery et Ajax
      • Bonnes pratiques
    • Guide de l'administrateur système
    • Guide du vendeur
      • Exemples de promotions
      • Nos bons conseils
    • Questions fréquentes
    • Dépannage
  • Documentación española 1.5
    • Acerca de PrestaShop 1.5
    • Introducción
      • Lo que necesita para empezar
    • Guía del usuario
      • Formación
      • Personalización de su tienda
      • Exploración del front-office
      • Conexión al back-office de PrestaShop
      • Primeros pasos con PrestaShop 1.5
      • Añadir productos y categorías de productos
      • Una mirada interna al catálogo
      • Gestionar pedidos
      • Gestionar clientes
      • Crear reglas de precios y cupones
      • Gestionar el transporte
      • Comprender la Configuración Local
      • Gestionar módulos y temas
      • Configurar los Módulos Nativos
      • Comprender las Preferencias
      • Comprender los Parámetros avanzados
      • Administrar el Back-Office
      • Comprender las estadísticas
      • Gestión avanzada de stock
      • Gestionar varias tiendas
    • Guía del Desarrollador
      • Tutoriales para Desarrolladores
        • Uso del Web Service de Prestashop
          • Capítulo 1 - Creación de acceso al Back Office
  • Документация на русском языке 1.5
    • Информация о PrestaShop 1.5
    • Новые функции в PrestaShop 1.5
    • Приступая к работе
      • Что нужно чтобы приступить к работе
      • Установка PrestaShop
      • Установка PrestaShop при помощи командной строки
      • Обновление и удаление PrestaShop
      • Прочая информация
    • Руководство пользователя
      • Обучение
      • Настройка вашего магазина
      • Изучение публичной части сайта
      • Бэк-офис PrestaShop
      • Первые шаги в PrestaShop 1.5
      • Добавление товаров и товарных категорий
      • Внутри каталога
      • Управление заказами
      • Работа с клиентами
      • Создание правил ценообразования корзины и ваучеров
      • Управление доставкой
      • Ориентация в локальных настройках
      • Управление модулями и темами
      • Настойка встроенных модулей
      • Ориентация в настройках
      • Ориентация в расширенных параметрах
      • Администрирование Back-Office
      • Ориентация в статистике
      • Расширенное управление запасами
      • Управление мультимагазином
Powered by GitBook
On this page
  • Overriding default behaviors
  • Overriding PrestaShop's classes and controllers
  • Overriding a module's behavior
  • Manipulating the override code manually
  • Sample code

Was this helpful?

  1. English documentation 1.5
  2. Developer Guide
  3. Developer tutorials

Overriding default behaviors

PreviousPublic and overloadable methodsNextUsing addJquery(), addJqueryPlugin() and addJqueryUI()

Last updated 4 years ago

Was this helpful?

Table of content

/*<![CDATA[*/ div.rbtoc1597308498835 {padding: 0px;} div.rbtoc1597308498835 ul {list-style: disc;margin-left: 0px;} div.rbtoc1597308498835 li {margin-left: 0px;padding-left: 0px;} /*]]>*/

Overriding default behaviors

PrestaShop enables you to override various default components and behaviors. This system consists of two major points:

  1. Overriding PrestaShop's own behavior (class files and controller files) in order to target a specific section of the required components.

  2. Overriding the visible parts of modules (Templates, JavaScript, style sheet language...) so that the themes can adapt better to them.

Overriding PrestaShop's classes and controllers

Overriding is a way to "override" class files and controller files. PrestaShop's ingenious class auto-loading function makes the "switch" to other files fairly simple. Thanks to PrestaShop's fully object-oriented code, you can rely on object inheritance to modify and add new behaviors, using the properties and methods of the various existing classes.

Classes and controllers are usually built following a certain norm. Here is the Product class and controller:

  • /classes/Product.php This class would be called ProductCore.

  • /controllers/front/ProductController.php This controller would be called ProductControllerCore.

You will need to create a PHP file and place it either of the override folders, depending on whether this file is part of a module, or distributed as-is. Indeed, since PrestaShop 1.5, there are two locations where you can place your overriding files: either at the root of the PrestaShop install, or within a module.

Overriding a class

In order to override the Product class, your file needs to be called Product.php and must feature a Product class that then extends ProductCore class.

The file can be placed in either of these locations:

  • /override/classes/Product.php

  • /modules/my_module/override/classes/Product.php

Overriding a controller

In order to override the ProductController class, your file needs to be called ProductController.php and must feature a ProductController class that then extends ProductControllerCore class.

The file can be placed in either of these locations:

  • /override/controllers/front/ProductController.php

  • /modules/my_module/override/controllers/front/ProductController.php

Overriding other behaviors

PrestaShop has certain files you can use to override elements such as displaying redirections (Tools.php) and measuring hook execution time (_Module.php), etc. you can enable them by removing the "_" prefix. For instance, rename _Tools.php into Tools.php. If there already exists a Tools.php override, you will have to merge it with yours.

Overriding a module's behavior

The modules are usually in the following format:

  • /modules/my_module/my_module.tpl

  • /modules/my_module/my_module.css

  • /modules/my_module/my_module.js

Since PrestaShop 1.5, they can and should also be in the following format:

  • /modules/my_module/views/templates/front/my_module.tpl

  • /modules/my_module/views/templates/front/my_module.css

  • /modules/my_module/views/templates/front/my_module.js

PrestaShop allows you to override or replace certain front-office module files with new ones within the same theme. The override is governed by the theme: once it contains a /modules folder (or more!), PrestaShop will browse its content for files which have the same name and path as those of existing modules, and replace these with the new ones.

This means, for PrestaShop 1.4-compatible modules:

  • /themes/my_theme/modules/my_module/my_module.tpl

  • /themes/my_theme/css/modules/my_module/my_module.css

  • /themes/my_theme/js/modules/my_module/my_module.js

Since PrestaShop 1.5, the path is slightly longer

  • /themes/my_theme/modules/my_module/views/templates/front/my_module.tpl

  • /themes/my_theme/css/modules/my_module/views/templates/front/my_module.css

  • /themes/my_theme/js/modules/my_module/views/templates/front/my_module.js

In general, the proper path to override a .tpl, .js or .css file depends on the module's own path. That is the reason why if PrestaShop 1.5 has to work with a module without a view folder, it will need the same override path. In short, you can keep overriding code in 1.5 just as you did in 1.4.

The new files will be used when the customer loads your shop.

Contrary to the override code that is to be placed manually in the /override folder, module overrides are enabled as soon as the module is installed. During installation, overriding code is merge with those already in place (if any), otherwise they are copied to the /override folder at the root of the PrestaShop folder.

Manipulating the override code manually

Modules and themes may add an override to a default behavior, and PrestaShop takes care of reseting the /cache/class_index.php file.

But sometimes you need to add that overriding code yourself, manually uploading the file to your server. In that case, you need to trigger the regeneration of the /cache/class_index.php file yourself. This is done simply by deleting the file: if PrestaShop cannot find the file, it will regenerate it, taking all the overrides into account.

It is the same when manually removing an override: in order to reinstate the default behavior, you must delete the /cache/class_index.php file.

Sample code

Example 1

Using the MySQL.php data class is simply impossible while trying to enter data into a different database from PrestaShop's on the same MySQL Server. (Really!)

The solution is to use the following override of the MySQLCore class:

<?php
class MySQL extends MySQLCore
{
	public function __construct($server, $user, $password, $database, $newlink = false)
	{
		$this->_server = $server;
		$this->_user = $user;
		$this->_password = $password;
		$this->_type = _DB_TYPE_;
		$this->_database = $database;

		$this->connect($newlink);
	}
	
	public function connect($newlink = false)
	{
		if (!defined('_PS_DEBUG_SQL_'))
			define('_PS_DEBUG_SQL_', false);

		if ($this->_link = mysql_connect($this->_server, $this->_user, $this->_password, $newlink) )
		{
			if (!$this->set_db($this->_database))
				die(Tools::displayError('The database selection cannot be made.'));
		}
		else
			die(Tools::displayError('Link to database cannot be established.'));

		/* UTF-8 support */
		if (!mysql_query('SET NAMES \'utf8\'', $this->_link))
			die(Tools::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.'));
		return $this->_link;
	}
}
?>

To use it you have to instantiate the class as follows:

  • For local connection: new MySQL(DB_SERVER, DB_USER, DB_PASSWD, 'DB_name', true);

  • For remote connection: new MySQL(DB_SERVER, DB_USER, DB_PASSWD, 'DB_name', true);

The last parameter forces the creation of a MySQL connection.

Example 2

/*
 * Create a cron task to make periodical database backup
*/
class AdminTab extends AdminTabCore{
	public function ajaxProcess()
	{			 
		// Here we call the same thing as if we did the old way
		// + with "if": maybe we want to limit its use to only adding backup
		// note: find yourself a way to get the file link if you want to send it by mail!
		if (isset($_REQUEST['addbackup']))
			return $this->postProcess();
	} 

	public function displayAjax()
	{
		if (sizeof($this->_errors) > 0)
		{
			// handle errors 
			// for example, send mail with all error msg
			$content = '';
			foreach($this->_errors as $errorMsg)
			 $content .= $errorMsg;

			 $lang = Configuration::get('PS_LANG_DEFAULT');
			 // here we send a mail to give the result of the process
			 // notice: you have to create template mails files
			 Mail::Send($lang, 'backuptaskdone', '[autobackup] report backup error', array('backup_link'=>)), $to); 
		}
		else
		{
			// no error, but maybe we want a mail?
			if(Configuration::get('PS_NOTICE_SUCCEED_BACKUP')) 
			{
				// fileAttachment available, see 9th param of Send() method in classes/Mail.php
				// + we can add a condition "if (Configuration::get('PS_AUTOBACKUP_SEND_FILE'))"
				Mail::Send($lang, 'backuptaskerror', '[autobackup] report backup error', array('vars to use in tpl'), $to); 
			}
		}
	return true;
	}
}
/*
 * This override allows you to use ajax-tab.php to make any admin action.
 * Use it for crontask for example
*/
class AdminTab extends AdminTabCore {
	public function ajaxProcess()
	{
		return $this->postProcess();
	}
}

Example 3

/*
 * With this override, you have a new Smarty variable called "currentController" available in header.tpl
 * This allows you to use a different header if you are on a product page, category page or home.
 */
class FrontController extends FrontControllerCore {
	public function initHeader()
	{
		self::$smarty->assign('currentController', get_class($this));
		return parent::initHeader();
	}
}
Overriding default behaviors
Overriding PrestaShop's classes and controllers
Overriding a class
Overriding a controller
Overriding other behaviors
Overriding a module's behavior
Manipulating the override code manually
Sample code
Example 1
Example 2
Example 3