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
  • HelperForm
  • Form declaration
  • Basic declaration
  • Generating specific elements
  • Other HTML elements

Was this helpful?

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

HelperForm

PreviousHelpersNextHelperOptions

Last updated 4 years ago

Was this helpful?

Table of contents

HelperForm

This helper is used to generate an edition form for an object of type ObjectModel. Example: editing the client's profile.

Form declaration

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

$this->fields_form = array(    
  'legend' => array(        
    'title' => $this->l('Edit carrier'),                     // This is the name of the fieldset, which can contain many option fields
    'image' => '../img/admin/icon_to_display.gif'            // The icon must, if there is one, must be of the size 16*16
  ),    
  'input' => array(        
    array(            
      'type' => {'text', 'select', 'textarea', 'radio', 'checkbox', 'file', 'shop', 'asso_shop', 'free', 'color'},
      ['label'] => $this->l('Shipping method'),              // Theoretically optional, but in reality each field has to have a label
      'name' => 'shipping_method',                           // The name of the object property from which we get the value
      ['required'] => {true, false},                         // If true, PrestaShop will add a red star next to the field
      ['desc'] => $this->l('Description displayed under the field'),
      ['hint'] => $this->l('Invalid characters:').' <>;=#{}' // This is displayed when the mouse hovers the field.
      ['suffix'] => 'kg'                                     // This is displayed after the field (ie. to indicate the unit of measure)
      ['options'] => array(                                  // This is only useful if type == select
        'query' => $array_of_rows,                           // $array_of_rows must contain an array of arrays, inner arrays (rows) being mode of many fields	
        'id' => 'id_carrier',                                // The key that will be used for each option "value" attribute
      ),
      ['values'] => array(                                   // This is only useful if type == radio
        array(
          'id' => 'active_on',
          'value' => 1,
          'label' => $this->l('Enabled')
        ),
        array(
          'id' => 'active_off',
          'value' => 0,
          'label' => $this->l('Disabled')
        )
      ),
      [is_bool] => {true, false},                            // This is only useful if type == radio. It display a "yes or no" choice.
      ['empty_message'] => $this->l('To be displayed when the field is empty'),
      ['lang'] => {true, false},                             // Is the field multilang?
     ),
    array(          
      //another field      
    ),    
  ),
  'submit' => array(
    'title' => $this->l('   Save   '),                       // This is the button that saves the whole fieldset.
    'class' => 'button'    
  )
);

If you want to use the "color" type, you can add the "color mColorPickerInput" classes

Basic declaration

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

$this->fields_form = array(
  'legend' => array(        
    'title' => $this->l('Edit carrier'),        
    'image' => '../img/admin/icon_to_display.gif'    
  ),    
  'input' => array(        
    array(            
      'type' => 'text',
      'name' => 'shipping_method',
     ),
  ),
  'submit' => array(
    'title' => $this->l('Save'),        
    'class' => 'button'    
  )
);

This specific code generates this HTML code (simplified here for readability reasons):

<form id="_form">
  <fieldset id="fieldset_main_conf">
    <legend>
      <img alt="Edit carrier" src="../img/admin/icon_to_display.gif">Edit carrier
    </legend>
    <div class="margin-form">
      <input type="text" class="" value="" id="shipping_method" name="shipping_method">
    </div>
    <div class="clear"></div>
    <div class="margin-form">
      <input type="submit" class="button" name="" value="Save" id="_form_submit_btn">
    </div>
  </fieldset>
</form>

Generating specific elements

The 'input' variable of the form declaration takes an array containing the content of your form. Using the various offered possibilities, you can build just about any type of form, and be assured that it will comply with PrestaShop's style and form processing.

You can use as many element arrays as necessary for your form, one after the other.

Text input

Here is how to generate a basic <input> element:

array(
  'type'     => 'text',                                // This is a regular <input> tag.
  'label'    => $this->l('Name'),                      // The <label> for this <input> tag.
  'name'     => 'name',                                // The content of the 'id' attribute of the <input> tag.
  'size'     => 50,                                    // The content of the 'size' attribute of the <input> tag.
  'required' => true,                                  // If set to true, this option must be set.
  'desc'     => $this->l('Please enter your name.')    // A help text, displayed right next to the <input> tag.
),

Selector

Here is how to generate a <select> element:

array(
  'type' => 'select',                              // This is a <select> tag.
  'label' => $this->l('Shipping method:'),         // The <label> for this <select> tag.
  'desc' => $this->l('Choose a shipping method'),  // A help text, displayed right next to the <select> tag.
  'name' => 'shipping_method',                     // The content of the 'id' attribute of the <select> tag.
  'required' => true,                              // If set to true, this option must be set.
  'options' => array(
    'query' => $options,                           // $options contains the data itself.
    'id' => 'id_option',                           // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array.
    'name' => 'name'                               // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array.
  )
),

The content of the selector is stored in the $options variable, which is an array of arrays. It must contain two keys: id and name.

$options can take this value:

$options = array(
  array(
    'id_option' => 1,                 // The value of the 'value' attribute of the <option> tag.
    'name' => 'Method 1'              // The value of the text content of the  <option> tag.
  ),
  array(
    'id_option' => 2,
    'name' => 'Method 2'
  ),
);

...but of course, you would be better off generating such an array of arrays yourself, from the data stored in PrestaShop. For instance, here is how to display a gender (social title) selector:

$options = array();
foreach (Gender::getGenders((int)Context::getContext()->language->id) as $gender)
{
  $options[] = array(
    "id" => (int)$gender->id,
    "name" => $gender->name
  );
}

Checkbox

Here is how to generate a <input> of type "checkbox":

array(
  'type'    => 'checkbox',                         // This is an <input type="checkbox"> tag.
  'label'   => $this->l('Options'),                // The <label> for this <input> tag.
  'desc'    => $this->l('Choose options.'),        // A help text, displayed right next to the <input> tag.
  'name'    => 'options',                          // The content of the 'id' attribute of the <input> tag.
  'values'  => array(
    'query' => $options,                           // $options contains the data itself.
    'id'    => 'id_option',                        // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array.
    'name'  => 'name'                              // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array.
  ),
),

Just as for a selector input, check boxes take an array of arrays as the value of $options.

Radio button

Here is how to generate a <input> of type "radio":

array(
  'type'      => 'radio',                               // This is an <input type="checkbox"> tag.
  'label'     => $this->l('Enable this option'),        // The <label> for this <input> tag.
  'desc'      => $this->l('Are you a customer too?'),   // A help text, displayed right next to the <input> tag.
  'name'      => 'active',                              // The content of the 'id' attribute of the <input> tag.
  'required'  => true,                                  // If set to true, this option must be set.
  'class'     => 't',                                   // The content of the 'class' attribute of the <label> tag for the <input> tag.
  'is_bool'   => true,                                  // If set to true, this means you want to display a yes/no or true/false option.
                                                        // The CSS styling will therefore use green mark for the option value '1', and a red mark for value '2'.
                                                        // If set to false, this means there can be more than two radio buttons, 
                                                        // and the option label text will be displayed instead of marks.
  'values'    => array(                                 // $values contains the data itself.
    array(
      'id'    => 'active_on',                           // The content of the 'id' attribute of the <input> tag, and of the 'for' attribute for the <label> tag.
      'value' => 1,                                     // The content of the 'value' attribute of the <input> tag.	
      'label' => $this->l('Enabled')                    // The <label> for this radio button.
    ),
    array(
      'id'    => 'active_off',
      'value' => 0,
      'label' => $this->l('Disabled')
    )
  ),
),

Note that you have to use the "t" CSS class on your labels in order to have the proper styling (but you can redefine that class using the "class" variable).

Other HTML elements

The type variable of the element declaration makes it possible to generate just about any kind of <input> element: text, select, textarea, radio, checkbox, file and many others! See the list of available types here: You can also use some PrestaShop specific: shop, asso_shop, free, color. Try them out!

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input
HelperForm
Form declaration
Basic declaration
Generating specific elements
Text input
Selector
Checkbox
Radio button
Other HTML elements