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 module with both front-end and back-end controllers
  • Creating a new data table
  • Creating the model
  • Creating the module's bootstrap file
  • Creating the hook's view
  • Creating the front-office controller
  • Creating the back-office controller
  • Adding the controller to the back-office

Was this helpful?

  1. English documentation 1.5
  2. Developer Guide

Creating a module with both front-end and back-end controllers

PreviousCreating a front-office moduleNextHooks in PrestaShop 1.5

Last updated 4 years ago

Was this helpful?

Table of contents

Creating a module with both front-end and back-end controllers

Creating a new data table

Add a new table to your PrestaShop database. Name this table ps_opinion.

id_opinion | int(10) unsignedid_customer | int(10) unsignedopinion | enum('AVERAGE','GOOD','VERY_GOOD')active | tinyint(1) unsigned

Creating the model

Variables

/* models/opinion.php */class Opinion extends ObjectModel{ public $id_opinion; public $id_customer; public $opinion; public $active;

Model definition

public static $definition = array( 'table' => 'opinion', 'primary' => 'id_opinion', 'multilang' => false, 'fields' => array( 'id_opinion' => array( 'type' => ObjectModel :: TYPE_INT ), 'id_customer' => array( 'type' => ObjectModel :: TYPE_INT, 'required' => true ), 'opinion' => array( 'type' => ObjectModel :: TYPE_STRING, 'required' => true ), 'active' => array( 'type' => ObjectModel :: TYPE_BOOL, required' => true ) ));

Functions

public static function findAll() { $sql = 'select * from ' . _DB_PREFIX_ . 'opinion where active = 1'; if ($rows = Db :: getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql)) { return ObjectModel :: hydrateCollection(__CLASS__, $rows); } return array(); } public function getCustomerName() { $customer = new Customer($this->id_customer); return $customer->firstname . ' ' . $customer->lastname; }}

Creating the module's bootstrap file

<?phprequire_once dirname(__FILE__) . '/models/Opinion.php';class CustomerOpinion extends Module{ public function __construct() { $this->name = 'customeropinion'; $this->tab = 'front_office_features'; $this->version = 1.0; $this->author = 'Me'; $this->displayName = $this->l('Customer Opinion'); $this->description = $this->l('Customer Opinion'); parent::__construct(); } public function install() { return parent::install() && $this->registerHook('leftColumn'); } public function hookDisplayLeftColumn($params) { return $this->display(__FILE__, 'left-column.tpl'); }}

Creating the hook's view

The left-column.tpl file is located in the /views/templates/hook folder.

{* Filename: left-column.tpl *}<a href="{$link->getModuleLink('customeropinion')}">{l s='Give my opinion' mod='customeropinion'}</a>

The getModuleLink() function makes it possible to add a link to the module's controller. Here is its signature: $link->getModuleLink($module, $controller = 'default', array $params = array(), $ssl = false, $id_lang = null)

Creating the front-office controller

The module's controller, default.php, is located in the /controllers/front folder.

class helloWorldDefaultModuleFrontController extends ModuleFrontController{ public function initContent() { parent::initContent(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($opinion = Tools::getValue('opinion', false)) { $opinionObj = new Opinion(); $opinionObj->id_customer = $this->context->customer->id; $opinionObj->active = false; $opinionObj->opinion = $opinion; $opinionObj->add(); $link = new Link(); Tools::redirect($link->getModuleLink('customeropinion', 'default')); } } $opinions = Opinion::findAll(); $this->context->smarty->assign('opinions', $opinions); $this->setTemplate('form.tpl'); }}

The template for the controller, form.tpl, is located in the /views/templates/front folder.

<h2>{l s='Give your opinion' mod='customeropinion'}</h2><form method="post" class="std"> <fieldset> <label for="opinion" id="opinion">{l s='Our website is...' mod='customeropinion'}</label> <select name="opinion"> <option>--</option> <option value="VERY_GOOD">{l s='Very Good' mod='customeropinion'}</option> <option value="GOOD">{l s='Good' mod='customeropinion'}</option> <option value="AVERAGE">{l s='Average' mod='customeropinion'}</option> </select> <input type="submit" class="button" value="{l s='Give my opinion' mod='customeropinion'}" /> </fieldset></form><hr /><h3>{l s='What people think' mod='customeropinion'}</h3><table style="width: 100%;"> {foreach from=$opinions item=opinion} <tr> <td>{$opinion->getCustomerName()}</td> <td>{$opinion->opinion}</td> </tr> {/foreach}</table>

Creating the back-office controller

The module's controller, AdminOpinion.php, is located in the /controllers/admin folder.

By convention, all back-office controllers should be named with the "Admin" prefix.

class AdminOpinionController extends ModuleAdminController{ public function __construct() { $this->table = 'opinion'; $this->className = 'Opinion'; parent::__construct(); $this->fields_list = array( 'id_opinion' => array( 'title' => '#' ), 'id_customer' => array( 'title' => $this->module->l('Customer'), 'callback' => 'getCustomerName' ), 'opinion' => array( 'title' => $this->module->l('Opinion') ), 'active' => array( 'title' => $this->module->l('Valider'), 'active' => 'status' ) ); $this->actions = array('delete'); } public function getCustomerName($echo, $row) { $id_customer = $row['id_customer']; $customer = new Customer($id_customer); return $customer->firstname . ' ' . $customer->lastname; }}

Adding the controller to the back-office

In its current state, the module's controller will not appear automatically in the back-office interface: you have to add it yourself, manually.

This is done using the tool in the "Menus" pages, under the "Administration" menu. See the documentation for this page in the PrestaShop 1.5 User Guide.

Creating a module with both front-end and back-end controllers
Creating a new data table
Creating the model
Variables
Model definition
Functions
Creating the module's bootstrap file
Creating the hook's view
Creating the front-office controller
Creating the back-office controller
Adding the controller to the back-office