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
  • Creating a front-office module
  • Organizing your module
  • Creating the bootstrap file
  • Building the config.xml file
  • Adding a configuration page
  • Implementing hooks
  • Template and CSS files

Was this helpful?

  1. English documentation 1.5
  2. Developer Guide

Creating a front-office module

PreviousCreating a PrestaShop moduleNextCreating a module with both front-end and back-end controllers

Last updated 4 years ago

Was this helpful?

Table of contents

Creating a front-office module

Organizing your module

A module is made of a lot of files, all stored in a folder that bears the same name as the module, that folder being in turn stored in the /modules folder at the root of the main PrestaShop folder.

Default files and folders for a PrestaShop 1.5 module:

  • "Bootstrap" file: name_of_the_module.php

  • Translation files: fr.php, en.php, es.php, etc., all in the /translations sub-folder

  • Cache configuration file: config.xml

  • Module-specific controllers, all in the /controllers sub-folder

  • Class-overriding code, all in the /override sub-folder (automatic install/uninstall using copy or merge)

  • View files: JavaScript, Models, CSS files, etc.:

    • /views/css sub-folder for CSS files

    • /views/js sub-folder for JavaScript files

    • /views/templates/front sub-folder for files used by the module controller

    • /views/templates/hooks sub-folder for files used by the module's hooks

  • 16x16 module logo: name_of_the_module.jpg (JPG format)

  • 32x32 module logo: name_of_the_module.png (PNG format)

The module we are going to create in called "Hello World!". Therefore, its folder is /modules/helloworld, and its bootstrap file must be /modules/helloworld/helloworld.php, with a HelloWorld class defined inside.

Creating the bootstrap file

Here is a very basic first file for the module, named helloworld.php:

<?phpif (!defined('_PS_VERSION_')) exit;class HelloWorld extends Module{}

At this stage, the module can only be seen in the "Modules" page in the back-office, in the "Other modules" section.

Adding a constructor

Let's add a first method to our bootstrap code. This method will initialize the module's variables.

<?phpif (!defined('_PS_VERSION_')) exit;class HelloWorld extends Module{ public function __construct() { $this->name = 'helloworld'; $this->tab = 'front_office_features'; $this->version = '1.0'; $this->author = 'Me, myself and I'; // New in Prestashop 1.5 $this->ps_versions_compliancy = array('min' => '1.5', 'max' => '1.6'); // required Prestashop 1.5 $this->dependencies = array('blockcart'); // This module needs the 'blockcart' module in order to work properly. parent::__construct(); $this->displayName = $this->l('Hello World'); $this->description = $this->l('This is a sample module.'); $this->confirmUninstall = $this->l('Are you sure you want to uninstall?'); if (!Configuration::get('HELLO_WORLD_NAME')) $this->warning = $this->l('No name provided'); }}

$this->name must be the same as the module's folder name!

$this->tab is meant to indicate in which module category the module should reside when displayed in the back-office module list. It can take one of the following values:

  • administration: Administration

  • advertising_marketing: Advertising & Marketing

  • analytics_stats: Analytics & Stats

  • billing_invoicing: Billing & Invoices

  • checkout: Checkout

  • content_management: Content Management

  • export: Export

  • front_office_features: Front Office Features

  • i18n_localization: I18n & Localization

  • market_place: Market Place

  • merchandizing: Merchandizing

  • migration_tools: Migration Tools

  • others: Other Modules

  • payments_gateways: Payments & Gateways

  • payment_security: Payment Security

  • pricing_promotion: Pricing & Promotion

  • quick_bulk_update: Quick / Bulk update

  • search_filter: Search & Filter

  • seo: SEO

  • shipping_logistics: Shipping & Logistics

  • slideshows: Slideshows

  • smart_shopping: Smart Shopping

  • social_networks: Social Networks

The install() and uninstall() methods

These two methods make it possible to control what happens when the store administrator installs or uninstalls the module.

In this example, we perform the following tasks during installation:

  • check that the module is not already installed

  • check that the module is not added to the leftColumn hook

  • check that the module is not added to the header hook

  • create the HELLO_WORLD_NAME configuration setting, setting its value to "World"

public function install(){ if (Shop::isFeatureActive()) Shop::setContext(Shop::CONTEXT_ALL); if (!parent::install() OR !$this->registerHook('leftColumn') OR !$this->registerHook('header') OR !Configuration::updateValue('HELLO_WORLD_NAME', 'World')) return false; return true;}

For its part, the uninstallation method simply deletes the HELLO_WORLD_NAME configuration setting.

public function uninstall(){ if (!parent::uninstall() || !Configuration::deleteByName('HELLO_WORLD_NAME') ) return false; return true;}

Building the config.xml file

This file makes it possible to optimize the loading of the module list in the back-office.

<?xml version="1.0" encoding="UTF-8" ?><module> <name>helloworld</name> <displayName>Hello World></displayName> <version>1.0></version> <description>This is a sample module.</description> <author>Moi></author> <tab>front_office_features></tab> <confirmUninstall>Are you sure you want to uninstall?</confirmUninstall> <is_configurable>1</is_configurable> <need_instance>1</need_instance> <limited_countries></limited_countries></module>

A few details:

  • is_configurable indicates whether the module has a configuration page or not.

  • need_instance indicates whether an instance of the module must be created when it is displayed in the module list. This can be useful if the module has to perform checks on the PrestaShop configuration, and display warning message accordingly.

  • limited_countries is used to indicate the countries to which the module is limited. For instance, if the module must be limited to France and Spain, use <limited_countries>fr,es</limited_countries>.

This module can be created automatically by PrestaShop.

Adding a configuration page

Your module can get a "Configure" link in the back-office module list, and therefore let the user change some settings. This "Configure" link appears with addition of the getContent() method.

public function getContent(){ if (Tools::isSubmit('submit'.$this->name)) { $HELLO_WORLD_NAME = strval(Tools::getValue('HELLO_WORLD_NAME')); if (!$HELLO_WORLD_NAME OR empty($HELLO_WORLD_NAME) OR !Validate::isGenericName($HELLO_WORLD_NAME)) $output .= $this->displayError( $this->l('Invalid Configuration value') ); else { Configuration::updateValue('HELLO_WORLD_NAME', $HELLO_WORLD_NAME); $output .= $this->displayConfirmation($this->l('Settings updated')); } } return $output.$this->displayForm();}

The configuration form itself is displayed with the displayForm() method:

public function displayForm(){ // Get default Language $default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); // Init Fields form array $fields_form[0]['form'] = array( 'legend' => array( 'title' => $this->l('Settings'), ), 'input' => array( array( 'type' => 'text', 'label' => $this->l('Configuration value'), 'name' => 'HELLO_WORLD_NAME', 'size' => 20, 'required' => true ) ), 'submit' => array( 'title' => $this->l('Save'), 'class' => 'button' ) ); $helper = new HelperForm(); // Module, Token and currentIndex $helper->module = $this; $helper->name_controller = $this->name; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name; // Language $helper->default_form_language = $default_lang; $helper->allow_employee_form_lang = $default_lang; // title and Toolbar $helper->title = $this->displayName; $helper->show_toolbar = true; // false -> remove toolbar $helper->toolbar_scroll = true; // yes - > Toolbar is always visible on the top of the screen. $helper->submit_action = 'submit'.$this->name; $helper->toolbar_btn = array( 'save' => array( 'desc' => $this->l('Save'), 'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name. '&token='.Tools::getAdminTokenLite('AdminModules'), ), 'back' => array( 'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'), 'desc' => $this->l('Back to list') ) ); // Load current value $helper->fields_value['HELLO_WORLD_NAME'] = Configuration::get('HELLO_WORLD_NAME'); return $helper->generateForm($fields_form);}

Implementing hooks

As is, the module does not do much. In order to display something on the front-office, we have to add support for a few hooks. This is done by implementing the hooks' methods:

  • hookDisplayLeftColumn(): will hook code into the left column – in our case, it will fetch the HELLO_WORLD_NAME module setting and display the module's template file, helloworld.tpl

  • hookDisplayRightColumn(): will simply do the same as hookDisplayLeftColumn()

  • hookDisplayHeader(): will add a link to our CSS file, /views/css/helloworld.css

public function hookDisplayLeftColumn($params){ $this->context->smarty->assign(array( 'name' => Configuration::get('HELLO_WORLD_NAME') )); return $this->display(__FILE__, 'helloworld.tpl');} public function hookDisplayRightColumn($params){ return $this->hookDisplayLeftColumn($params);} public function hookDisplayHeader(){ $this->context->controller->addCSS($this->_path.'views/css/helloworld.css', 'all');}

Template and CSS files

Here is our template file, located in /views/templates/hook/helloworld.tpl:

<div id="hello_world_block_left" class="block"> <h4>{l s='Message' mod='helloworld'}</h4> <div class="block_content"> <p>Hello, {if isset($name) AND $name}{$name}{else}World{/if} </p> </div></div>

...and our CSS file, located in /views/css/helloworld.css:

div#hello_world_block_left p { font-weight: bold }

Creating a front-office module
Organizing your module
Creating the bootstrap file
Adding a constructor
The install() and uninstall() methods
Building the config.xml file
Adding a configuration page
Implementing hooks
Template and CSS files