# How to Add a Configuration Page

You need to allow the users to configure the module. And for that, your module should have the configure link at the back office under the Module and Services tab, in the module list.

The Configure link appears when you add the getContent() method to your main class. This is the standard QloApps method, its purpose is to inform the back office that the module consists of a configuration page and it has to display the configuration link.

But the getContent() public method in the module object only links appear, not create a configuration page. You will need to create a configuration page, and we will explain how.

# The getContent() method

First, here is the complete code for the getContent() method:

public function getContent()
{
    $html = '';
    if (Tools::isSubmit('submit'.$this->name)) {
        $myConfigurationValue = strval(Tools::getValue('MY_CONFIGURATION_NAME'));

        if (!$myConfigurationValue || !Validate::isGenericName($myConfigurationValue)) {
            $html .= $this->displayError($this->l('Invalid configuration value.'));
        } else {
            Configuration::updateValue('MY_CONFIGURATION_NAME', $myConfigurationValue);
            $html .= $this->displayConfirmation($this->l('Settings updated.'));
        }
    }

    return $html.$this->displayForm();
}

When configuration page is loaded the getContent() method is called first. And that is why it is used to first update any value that is submitted by any form that exists on the configuration page.

Here is a line by line explanation:

  1. Tools::isSubmit() is a method to check the validity of the indicated form. If the configuration form is not validated, the whole if() block will be skipped and QloApps will only use the last line, which displays the configuration with the current values, as generated by the displayForm() method.
  2. Tools:getValue() retrieve the content of the POST or GET array to get the value of the specified variable. With this QloApps retrieve the module form variable value, turn the value into a text string using the strval() method, and stores it in the $module_name PHP variable.
  3. Then it checks for the existence of actual content in $module_name, including the use of Validate::isGenericName(). The Validate object has many data validation methods, one of which is isGenericName(), this method helps you keep only strings that are valid QloApps names i.e. a string that does not contain special characters, for short.
  4. In case any of the above checks fail, the configuration will open with an error message, showing that the form validation failed. The $output variable, that contains the final rendition of the HTML code of the configuration page begins with an error message, using QloApps displayError() method. This method returns the correct HTML code for our need, and since that code is first in $output, this means the configuration will open with that message.
  5. And if all the checks are successful, then the value will be stored in our database. As we saw earlier, the Configuration object has just the updateValue() method which will store the new value for module_name in the configuration data table. And then we add a message to the user that the value is saved. We use displayConfirmation() method to add that message as the first data in the $output variable – and therefore, at the top of the page.
  6. At the end, we use the custom displayForm() method to add content to $output and return that content to the page. Note that the code for displayForm() could have included right within getContent(), but the two are separated for readability and separation of concerns.

# Displaying the form

The configuration form itself is displayed with the displayForm() method. Here is its code:

public function displayForm()
{
    // Get default language
    $defaultLang = (int) Configuration::get('PS_LANG_DEFAULT');

    // Init Fields form array
    $fieldsForm[0]['form'] = array(
        'legend' => array(
            'title' => $this->l('Settings'),
        ),
        'input' => array(
            array(
                'type' => 'text',
                'label' => $this->l('Configuration value'),
                'name' => 'VARIABLE_NAME',
                'size' => 20,
                'required' => true
            )
        ),
        'submit' => array(
            'title' => $this->l('Save'),
            'class' => 'btn btn-default pull-right'
        )
    );

    $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 = $defaultLang;
    $helper->allow_employee_form_lang = $defaultLang;

    // 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['VARIABLE_NAME'] = Configuration::get('VARIABLE_NAME');

    return $helper->generateForm($fieldsForm);
}

This block of code helps in making the build forms easily while using some QloApps methods.

Here is the line wise explanation:

  1. With the Configuration::get() method, we retrieve the value of the currently chosen language ("PREFIX_LANG_DEFAULT"). For security reasons, we cast the variable into an integer using (int).

  2. While preparing to generate the form, we must build an array of the various titles, textfields and other form specifics. At the end, we create the $fieldsForm variable, which will contain a multidimensional array. Each of the arrays it features has the detailed description of the tags the form must contain. From this variable, QloApps will render the HTML form as it is described. For instance:

    'input' => array(
        array(
            'type' => 'text',
            'label' => $this->l('Configuration value'),
            'name' => 'VARIABLE_NAME',
            'size' => 20,
            'required' => true
        ))
    

    ...generates the following HTML tags:

    <label>Configuration value </label>
    <div class="margin-form">
    <input id="VARIABLE_NAME" class="" type="text" size="20" value="my friend" name="VARIABLE_NAME">
    <sup>*</sup>
    <div class="clear"></div>
    
  3. We then create an instance of the HelperForm class which is explained further in this document.

  4. Once the HelperForm settings are done, we generate the form based on the content of the $fieldsForm variable.

# Using HelperForm

HelperForm is one of the helper methods along with HelperOptions, HelperList, HelperView and HelperHelpAccess. They allow you to generate standard HTML elements for the back office as well as for module configuration pages.

Here is our sample code, as a reminder:

$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 = $defaultLang;
$helper->allow_employee_form_lang = $defaultLang;

// 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['VARIABLE_NAME'] = Configuration::get('VARIABLE_NAME');

return $helper->generateForm($fieldsForm);

Our example uses several of HelperForm's attributes: they need to be set before we generate the form itself from the $fieldsForm variable:

  • $helper->module: requires the instance of the module that will use the form.
  • $helper->name_controller: requires the name of the module.
  • $helper->token: requires a unique token for the module. getAdminTokenLite() helps us generate one.
  • $helper->default_form_language: requires the default language for the shop.
  • $helper->allow_employee_form_lang: requires the default language for the shop.
  • $helper->title: requires the title for the form.
  • $helper->show_toolbar: requires a boolean value – whether the toolbar is displayed or not.
  • $helper->toolbar_scroll: requires a boolean value – whether the toolbar is always visible when scrolling or not.
  • $helper->submit_action: requires the action attribute for the form's <submit> tag.
  • $helper->toolbar_btn: requires the buttons that are displayed in the toolbar. In our example, the "Save" button and the "Back" button.
  • $helper->fields_value[]: this is where we can define the value of the named tag.

In the end, when everything is set up, we can call the generateForm() method, which will take care of putting it all together and, as its name says, generate the form that the user will use to configure the module's settings.

Here is the rendition of the form as it is presently written – which you can see by yourself by clicking on the "Configure" link for the module in the back office:

Change the value to whichever you like, click on the "Save" button, then go reload the homepage: your module is indeed updated with the new string!

# Saving form data

After admin submits the form, the request is send to the same URL along with submitCONTROLLERNAME parameter in POST data where CONTROLLERNAME is $helper->name_controller assigned in helper form.

To save form data, we will check form submit in getContent() and save data.

public function getContent()
{
    $html = '';
    if (Tools::isSubmit('submit'.$this->name)) {
        // Process data save here
        $myVarName = strval(Tools::getValue('MY_VAR_NAME'));
        if (!$myVarName || !Validate::isGenericName($myVarName)) {
            $html .= $this->displayError($this->l('Invalid Configuration value'));
        } else {
            Configuration::updateValue('MY_VAR_NAME', $myVarName);
            $html .= $this->displayConfirmation($this->l('Settings updated'));
        }
    }

    return $html.$this->displayForm();
}