Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 30 ยท Module Basics

A Module Configuration Page

Build a settings page for a PrestaShop module with getContent(), HelperForm, Configuration::get and updateValue, validation and flash messages, with a runnable stand-in.

Most modules need settings: an API key, a number of items to show, a switch that turns a feature on. PrestaShop gives you a standard place for this. When your module has a getContent() method, the module manager shows a Configure button, and clicking it calls that method. Whatever it returns is displayed inside the back office.

In this lesson you will build that page the classic way, with getContent(), a HelperForm, Configuration::get() and Configuration::updateValue(), and with validation and feedback messages. The real code is read-only; the stand-ins render a form from the same kind of definition array and validate a submission, so you can see the whole cycle (show form, receive data, validate, save, confirm) running.

The cycle in one picture

A settings page always follows the same loop:

flowchart TD
    A["Admin opens Configure"] --> B["getContent()"]
    B --> C{"Form submitted?"}
    C -->|"no"| E["Render form with saved values"]
    C -->|"yes"| D["Validate input"]
    D -->|"invalid"| F["Error message<br/>+ form again"]
    D -->|"valid"| G["Configuration::updateValue()<br/>+ confirmation message"]
    F --> E
    G --> E

The same method handles both display and saving: it checks for a submission first, then always renders the form.

getContent()

PHP
public function getContent()
{
    $output = '';

    if (Tools::isSubmit('submitHellomodule')) {
        $greeting = trim((string) Tools::getValue('HELLOMODULE_GREETING'));
        $limit = (int) Tools::getValue('HELLOMODULE_LIMIT');

        if ($greeting === '' || !Validate::isGenericName($greeting)) {
            $output .= $this->displayError(
                $this->trans('The greeting is empty or contains forbidden characters.', [], 'Modules.Hellomodule.Admin')
            );
        } elseif ($limit < 1 || $limit > 20) {
            $output .= $this->displayError(
                $this->trans('The limit must be between 1 and 20.', [], 'Modules.Hellomodule.Admin')
            );
        } else {
            Configuration::updateValue('HELLOMODULE_GREETING', $greeting);
            Configuration::updateValue('HELLOMODULE_LIMIT', $limit);
            Configuration::updateValue('HELLOMODULE_ENABLED', (bool) Tools::getValue('HELLOMODULE_ENABLED'));
            $output .= $this->displayConfirmation(
                $this->trans('Settings updated.', [], 'Admin.Notifications.Success')
            );
        }
    }

    return $output . $this->renderForm();
}

Walk through it:

  • Tools::isSubmit('submitHellomodule') is true when the form was posted with that submit name.
  • Tools::getValue() reads a value from $_POST or $_GET. It returns whatever the client sent, so it is untrusted input. Cast it ((int), (bool), (string)), trim it, and validate it before storing.
  • Validate::isGenericName() is one of many helpers on the Validate class (isEmail, isUnsignedInt, isUrl, isCleanHtml, and so on). Look at the class in your version for what is available and what each checks. isGenericName rejects characters such as <, >, =, { and }; read its source in your version for the exact rule.
  • displayError() and displayConfirmation() are methods of Module that return the HTML of a red or green notice box. You concatenate them in front of the form.
  • The method returns a string. It never echoes.

A note on terminology: because the page handles both showing and saving, newer code often splits this into postProcess() and renderForm(). That is purely organization. It can still be called from getContent().

Configuration::get and updateValue

Configuration is a key-value store backed by the configuration table:

PHP
Configuration::updateValue('HELLOMODULE_GREETING', 'Hello!');  // create or update
$greeting = Configuration::get('HELLOMODULE_GREETING');         // read, false if missing
Configuration::deleteByName('HELLOMODULE_GREETING');            // remove (use in uninstall)

Points to remember:

  • Prefix your keys with your module name in capitals (HELLOMODULE_...). All modules share one table, so a short generic key such as ENABLED would collide.
  • Values are stored as strings. Booleans become '1' or '0', integers become digit strings. Cast on reading: (int) Configuration::get('HELLOMODULE_LIMIT').
  • Configuration::get() returns false when a key does not exist, which looks the same as a stored empty value after casting. Set a default in install(), so the key always exists.
  • Values are cached in memory for the request, so reading a key many times is cheap.
  • In a multistore setup, updateValue() and get() accept additional arguments for a shop or shop group. Single-shop code can ignore them, but if your module may run in multistore, read the documentation for your version.
  • For translatable values (a greeting in several languages) pass an array keyed by language ID. See Translations and Multilingual Modules.

Building the form with HelperForm

HelperForm generates a standard back-office form from a PHP array, so that you do not write HTML and your page matches the rest of the admin. It also adds the security token for you.

PHP
protected function renderForm()
{
    $helper = new HelperForm();
    $helper->module = $this;
    $helper->table = $this->table;
    $helper->identifier = $this->identifier;
    $helper->default_form_language = (int) Configuration::get('PS_LANG_DEFAULT');
    $helper->submit_action = 'submitHellomodule';
    $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
        . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
    $helper->token = Tools::getAdminTokenLite('AdminModules');

    $helper->tpl_vars = [
        'fields_value' => [
            'HELLOMODULE_GREETING' => Tools::getValue('HELLOMODULE_GREETING', Configuration::get('HELLOMODULE_GREETING')),
            'HELLOMODULE_LIMIT' => Tools::getValue('HELLOMODULE_LIMIT', Configuration::get('HELLOMODULE_LIMIT')),
            'HELLOMODULE_ENABLED' => Tools::getValue('HELLOMODULE_ENABLED', Configuration::get('HELLOMODULE_ENABLED')),
        ],
        'languages' => $this->context->controller->getLanguages(),
        'id_language' => $this->context->language->id,
    ];

    return $helper->generateForm([$this->getConfigForm()]);
}

protected function getConfigForm()
{
    return [
        'form' => [
            'legend' => [
                'title' => $this->trans('Settings', [], 'Admin.Global'),
                'icon' => 'icon-cogs',
            ],
            'input' => [
                [
                    'type' => 'text',
                    'name' => 'HELLOMODULE_GREETING',
                    'label' => $this->trans('Greeting', [], 'Modules.Hellomodule.Admin'),
                    'desc' => $this->trans('Shown on the home page.', [], 'Modules.Hellomodule.Admin'),
                    'required' => true,
                    'col' => 6,
                ],
                [
                    'type' => 'text',
                    'name' => 'HELLOMODULE_LIMIT',
                    'label' => $this->trans('Limit', [], 'Modules.Hellomodule.Admin'),
                    'col' => 2,
                ],
                [
                    'type' => 'switch',
                    'name' => 'HELLOMODULE_ENABLED',
                    'label' => $this->trans('Enabled', [], 'Admin.Global'),
                    'is_bool' => true,
                    'values' => [
                        ['id' => 'on', 'value' => 1, 'label' => $this->trans('Yes', [], 'Admin.Global')],
                        ['id' => 'off', 'value' => 0, 'label' => $this->trans('No', [], 'Admin.Global')],
                    ],
                ],
            ],
            'submit' => [
                'title' => $this->trans('Save', [], 'Admin.Actions'),
            ],
        ],
    ];
}

The structure is the important part: a legend, a list of input definitions (each with type, name, label, optional desc, required, col), and a submit button. Types include text, textarea, select, switch, radio, checkbox, file, color and html. In fields_value, notice the two-step default: if the visitor just submitted an invalid form, Tools::getValue() returns what they typed, so they do not lose their input; otherwise the saved configuration value is used.

HelperForm is the classic approach and works in all current versions. Newer back-office pages use Symfony forms and Twig, which is the subject of Twig, Forms and Grids. A module can still ship a classic getContent() page, and many do.

Making the "Configure" button appear

The module manager shows Configure when the class has a getContent() method. It also needs $this->bootstrap = true; in the constructor for the form styling.

Rendering a form from a definition

The first stand-in does what HelperForm::generateForm() does in spirit: it takes the same shape of array and produces HTML, filling in values and escaping them. It is not HelperForm; the real one uses Smarty templates and adds a token and language handling.

PHP Render a settings form from a definition array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the first input: the stored text contains & and tags, and the renderer turns them into entities. Escaping when you output is a basic rule; the real HelperForm does the same through its templates.

Validation and messages: a full cycle

The second stand-in replays the getContent() logic against several simulated submissions and keeps the "database" as an array. It shows the order of operations: read, cast, validate, save, report.

PHP Handle submissions: validate, save, report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that the invalid submissions did not change $config: the module saves only when every check passes. Saving half of a form and then reporting an error confuses merchants.

Practical advice

  • Validate on the server. Browser checks are a convenience, never protection.
  • One message per problem is friendlier than a single generic error.
  • Do not store secrets in clear text in logs. API keys do live in Configuration, but never print them in error messages, and show only part of a key when you display it again.
  • Clean up in uninstall(). Every updateValue needs a matching deleteByName.
  • Defaults belong in install(), not in each place you read the value.
  • Prefix keys to avoid collisions with other modules.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes the "Configure" button appear for a module?

    The module manager shows Configure for modules whose class has getContent(). Its returned HTML is displayed in the back office.
  2. 2. Why should you cast and validate the result of Tools::getValue()?

    Tools::getValue() only reads request data. Treat it as untrusted, cast it to the expected type and check it before saving.
  3. 3. Which key name is best for a module setting?

    All modules share one configuration table, so a prefix with the module name prevents collisions.
  4. 4. What does getContent() return?

    getContent() must return the HTML, typically notices followed by the form.
  5. 5. In the validate-then-save cycle, when should updateValue() be called?

    Saving only valid input avoids half-saved forms and confusing messages.

Summary

  • A getContent() method returns the HTML of the configuration page and creates the Configure button.
  • Handle submission first (Tools::isSubmit, Tools::getValue, cast and validate), then always render the form.
  • Configuration::updateValue, get and deleteByName store prefixed, string-based settings; set defaults in install() and delete in uninstall().
  • HelperForm renders a form from an array and handles the token; displayError and displayConfirmation show feedback.
  • Validate on the server, save only valid data, and escape on output.

Next: Hooks: How Modules Plug In