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
  • HelperList
  • List declaration
  • Basic declaration
  • Enabling specific features
  • Adding an "Actions" column
  • Adding a "Details" row action
  • Ajax generalities

Was this helpful?

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

HelperList

PreviousHelperOptionsNextUsing helpers to overload a back-office template

Last updated 4 years ago

Was this helpful?

Table of contents

HelperList

This Helper is used to generate a table of elements. The elements can belong to ObjectModel-type objects, but they do not have to. Example: client list, order status list.

List declaration

Fields inside [brackets] are optional as per the HTML standard. Values between {curly braces} list the possible values for this field.

$this->fields_list = array(
  'country' => array(                              // First column.
    'title' => $this->l('Country'),                // Column name.
    'width' => 100,                                // Column width. At least one field should be set to 'auto' in order to grow with window size.
    ['align'] => {'left', 'center', 'right'},      // Content position inside the column (default 'left', optional).
    ['type'] => {'select', 'bool', 'date',         // Column format (optional).
      'datetime', 'decimal', 'float', 'percent', 
      'editable', 'price'}, 
    ['list'] => $this->countries_array,            // For type == select only. Content for the select drop down filter list (optional).
    ['filter_key'] => 'cl\!id_country'),           // Define a custom filter key to be used by the filter SQL request 
                                                   // (optional, default uses the array key name, ie. 'country').
    ['orderby'] => {true, false},                  // If true, list will be alphabetically ordered using this column values (optional, default false).
    ['search'] => {true, false},                   // If true, this column will have a search field (optional, default true).
    ['image'] => 's',                              // If set, an image will be displayed in this field located in the '/img' subfolder defined as value here (optional).
    ['image_id'] => 3,                             // If 'image' is set abd if 'image_id' is set, it will be used as the image filename, 
                                                   // else the record item id will be used (optional)
    ['icon'] => array(               	           // If set, an icon will be displayed with icon key matching the field value. 
      0 => 'disabled.gif',                         // Used in combination with type == bool (optional).
      1 => 'enabled.gif',
      'default' => 'disabled.gif'
    ),
    ['active'] => 'status',                        // If set, the field will be replaced by a clickable boolean switch for the item field (ie. 'status'). 
                                                   // An icon will display the current status.
    ['activeVisu'] => 'new_window',                // If set, the field will be replaced by an icon depending on the boolean value
                                                   // of the field specified (ie. 'new_window') (optional).
    ['callback'] => 'getOrderTotalUsingTaxCalculationMethod', // If set, the return value of the defined method call will be used as the field content (optional).
    ['callback_object'] => $cart,                  // If set in combination with 'callback', the method will be called from the provided object 
                                                   // instead of the current controller (optional).
    ['prefix'] => '0x',                            // If set, it will be displayed before the field value (optional).
    ['suffix'] => 'kg',                            // If set, it will be displayed after the field value (optional).
    ['currency'] => {true, false},                 // If set and type == price, the currency displayed will use the item currency and not the default currency (optional).
    ['maxlength'] => 90,                           // If set, the field value will be truncated if it has more characters than the numeric value set (optional).
    ['position'] => 'position',                    // If set to position, the field will display arrows and be drag and droppable, which will update position in db (optional).
    ['tmpTableFilter'] => {true, false},           // If set to true, the WHERE clause used to filter results will use the $_tmpTableFilter variable (optional, default false).
    ['havingFilter'] => {true, false},             // If set to true, the WHERE clause used to filter results will use the $_filterHaving variable (optional, default false).
    ['filter_type'] => {'int', 'bool', 'decimal'}, // Specify the value format when used in the filter where clause.
                                                   // Useful when "filter_type" is different from "type" (ie. type == select) (optional).
    ['color'] => 'color',                          // If set, the field value will appear inside a colored element. 
                                                   // The color used is the "color" index of the record and is in HTML name or hexadecimal format (optional).
    ['hint'] => $this->l('This is the quantity available in the current shop/group') // the hint will appear on column name hover (optional).
  ),
  'another_field' => array(                        // Second column.
    ...
  ),
  'another_field' => array(                        // third column.
    ...
  ),
);

Basic declaration

Removing all the optional fields, this is how to build a basic HelperList element:

private function initList()
{
    $this->fields_list = array(
        'id_category' => array(
            'title' => $this->l('Id'),
            'width' => 140,
            'type' => 'text',
        ),
        'name' => array(
            'title' => $this->l('Name'),
            'width' => 140,
            'type' => 'text',
        ),
    );
    $helper = new HelperList();
    
    $helper->shopLinkType = '';
    
    $helper->simple_header = true;
    
    // Actions to be displayed in the "Actions" column
    $helper->actions = array('edit', 'delete', 'view');
    
    $helper->identifier = 'id_category';
    $helper->show_toolbar = true;
    $helper->title = 'HelperList';
    $helper->table = $this->name.'_categories';
    
    $helper->token = Tools::getAdminTokenLite('AdminModules');
    $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
    return $helper;
}

This specific code generates this list:

Enabling specific features

Sortable header

By default, the list's header simply displays the name of each column.

In order to make the column sortable and searchable, you only have to disable one option:

$helper->simple_header = false;

By disabling the simple_header option, the list displays a more complex header:

Adding an "Actions" column

The above example directly builds a table with an action column, which comprises three actions: edit, delete, view.

$helper->actions = array('edit', 'delete', 'view');

Note that they will not work out of the box: while the action icons are there and can be clicked, nothing will happen when the user clicks until you have assigned proper code to these actions.

Adding a "Details" row action

Principle

You can define an "Details" action (or "+" action) in each row of a list. This action is useful if you want to show other information about the row (for example, the details of a sum).

This action is represented by a "+" if the details is shown and by a "-" if the details is hidden. The content is obtained through an Ajax request.

Example

There are two possible ways to displays:

  • The easy one is to re-use the table structure. See for instance the "Stock instant state" page, under the "Stock" menu (when the "Advanced Stock Management" option is enabled).

  • You can define your own structure (for example, to display a new table within the table). See for instance the "Stock Management" page, under the "Stock" menu (when the "Advanced Stock Management" option is enabled).

Add the action

To add the "Details" action, use the following function in the target AdminController:

$this->addRowAction('details');

Ajax generalities

Ajax requests must be generated by the ajaxProcess()method in your AdminController.

Only one element is sent to the request: the table row's id. You can get it by using:

(int)Tools::getValue('id');

This id is defined either in the $identifier class attribute, or by the table name ($table attribute), prefixed by "id_".

This function must display the result in JSON format.

Performing an Ajax request on the table's structure

The expected JSON format:

{
  use_parent_structure: true,  // Optional.
  data:                        // Here is the SQL result.
  [
    {field_name: 'value'}
  ],
  fields_display:              // $fieldsDisplay attribute for the AdminController.
}

Sample Ajax request code:

public function ajaxProcess()
{
  $query = 'SELECT * FROM mytable';
  echo Tools::jsonEncode(array(
    'data'=> Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query),
    'fields_display' => $this->fieldsDisplay
  ));
  die();
}

Performing an Ajax request using your own structure

The expected JSON format:

{
    use_parent_structure: false,
    data: '<p>My HTML content</p>'
}
HelperList
List declaration
Basic declaration
Enabling specific features
Sortable header
Adding an "Actions" column
Adding a "Details" row action
Principle
Example
Add the action
Ajax generalities
Performing an Ajax request on the table's structure
Performing an Ajax request using your own structure