Skip to content

Instantly share code, notes, and snippets.

@jonpontet
Created December 16, 2021 14:45
Show Gist options
  • Save jonpontet/9b3dbd65ca542f8cb068bc3b4ca6a68a to your computer and use it in GitHub Desktop.
Save jonpontet/9b3dbd65ca542f8cb068bc3b4ca6a68a to your computer and use it in GitHub Desktop.
How to add a settings config form to your custom module in PrestaShop
<?php
// Add all these functions to your custom module
/**
* Function to display content for your module in the Back Office
*
* @return string
*/
public function getContent()
{
$this->html = '';
$this->postProcess();
$this->html .= $this->renderForm();
return $this->html;
}
/**
* Create a config form for your module
* Called by getContent
*
* @return string
*/
public function renderForm()
{
$fields_form = array(
'legend' => array(
// Form title
'title' => $this->trans('Form name', array(), 'Modules.[module_name].Admin'),
'icon' => 'icon-cogs',
),
'input' => array(
// Add a for each config setting here as an array
array(
'type' => 'text',
'label' => $this->trans('Field name', array(), 'Modules.[module_name].Admin'),
'name' => 'CONFIG_SETTING_NAME',
),
),
'submit' => array(
'title' => $this->trans('Save', array(), 'Admin.Actions'),
'name' => 'submitConfig',
),
);
// Generic form handling that you normally don't need to change
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->fields_value = $this->getFormValues();
$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->default_form_language = (int)$this->context->language->id;
return $helper->generateForm(array(array('form' => $fields_form)));
}
/**
* Populates the values of the form fields
*
* @return array
*/
public function getFormValues()
{
$values = array(
// Add a line for each config setting
'CONFIG_SETTING_NAME' => Tools::getValue('CONFIG_SETTING_NAME', Configuration::get('CONFIG_NAME'))
);
return $values;
}
/**
* Looks for the form submissions and handles the saving
*/
protected function postProcess()
{
if (Tools::isSubmit('submitConfig')) {
$error = null;
// Update or create setting
if (!Configuration::updateValue('CONFIG_SETTING_NAME', Tools::getValue('CONFIG_SETTING_NAME'))) {
// Error message
$error = $this->trans('Cannot update settings', array(), 'Modules.[module_name].Admin');
}
if ($error) {
$this->html .= $this->displayError($error);
} else {
// Success message
$this->html .= $this->displayConfirmation($this->trans('Settings updated successfully', array(), 'Modules.[module_name].Admin'));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment