The module settings form in OpenCart consists of three parts: the controllerCode that receives a request and prepares data. More in the glossary → prepares field values, the Twig template displays them, and the handler validates the data and saves it. In OpenCart 3.0, this is a regular POST to the same route with the validate() method and a redirect. In OpenCart 4.1, the form is submitted via an AJAX request to a separate save() method, which returns JSON with errors for each field. Both schemes are described below using the built-in account and html modules as examples.
Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.
How is the form structured in OpenCart 3.0?
In 3.0, the same index() method both displays the form and handles its submission. The typical sequence is as follows:
- If the request method is
POSTandvalidate()returnstrue, the controller saves the data, putstext_successinto$this, and performs->session ->data['success'] $thisto the extensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → list with->response ->redirect() &type=module. - Otherwise, the controller collects data for the template. Errors from
$this->errorare placed into theerror_warning,error_namevariables, and so on, while field values are taken in priority order: first from POST (so the user does not lose their input after an error), then from saved settings, and then empty. - The template shows
error_warningas a general message at the top, and the field error in an<div class="text-danger">block below it.
Example
protected function validate() {
if (!$this->user->hasPermission('modify', 'extension/module/mymodule')) {
$this->error['warning'] = $this->language->get('error_permission');
}
if ((utf8_strlen($this->request->post['module_mymodule_title']) < 3) || (utf8_strlen($this->request->post['module_mymodule_title']) > 64)) {
$this->error['title'] = $this->language->get('error_title');
}
return !$this->error;
}
The private $error = array(); property is declared at the beginning of the class. The permission check goes first: without the modify permission, a user can view the form (access is enough for that) but cannot save it. For string length in 3.0, use utf8_strlen() rather than strlen(): a Cyrillic letter takes two bytes, so "Доставка" has a length of 16 under strlen(), not 8.
In 3.0, the "Save" button is placed in the page header, outside the form tag, and is tied to the form with the form="form-module" attribute, using id="form-module". This is a standard technique, and with it the button works without JavaScript. The controller-to-template cycle itself is described in the article OpenCart controller and passing data to the template.
What changed in OpenCart 4.1?
In 4.1, display and saving are separated. index() only shows the form and passes the save address to the template: $this. The form tag has the data-oc-toggle="ajax" attribute, and the general admin script admin/ intercepts the submission itself, sends a POST, and parses the JSON response.
What index() prepares
The display method in 4.1 is simpler than in 3.0 because it does not accept POST. It loads the language fileA PHP file with interface texts, separate for each language. More in the glossary → and sets the page title. Then it builds the breadcrumbsA navigation chain such as "Home → Category → Product." More in the glossary → ("Home" → "Extensions" → module name) and the save and back addresses, where the "Back" button leads to marketplace/ with &type=module. It takes field values directly from $this, and for an instance from getModule($module_id). Checking POST and showing errors, as in 3.0, is not needed here: after an AJAX save the page does not reload, and the entered values remain in the fields. Finally, index() adds header, column_left, footer and renders the template.
The save() method does not render a template or perform a redirect. It fills the $json array and returns it with the Content-Type: application/ header:
Example
public function save(): void {
$this->load->language('extension/mymodule/module/mymodule');
$json = [];
if (!$this->user->hasPermission('modify', 'extension/mymodule/module/mymodule')) {
$json['error']['warning'] = $this->language->get('error_permission');
}
$required = ['module_mymodule_title' => '', 'module_mymodule_email' => ''];
$post_info = $this->request->post + $required;
if (!oc_validate_length($post_info['module_mymodule_title'], 3, 64)) {
$json['error']['title'] = $this->language->get('error_title');
}
if ($post_info['module_mymodule_email'] && !oc_validate_email($post_info['module_mymodule_email'])) {
$json['error']['email'] = $this->language->get('error_email');
}
if (!$json) {
$this->load->model('setting/setting');
$this->model_setting_setting->editSetting('module_mymodule', $post_info);
$json['success'] = $this->language->get('text_success');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
The $this technique is taken from the built-in 4.1 modules: the + operator adds missing keys with default values, so validation does not fail with "Undefined array key" if a field was not sent. The JSON responses and browser-side handling are described in more detail in the article AJAX and JSON in OpenCart controllers.

How do errors from JSON reach the right field?
In 4.1, you do not need to write JavaScript to display errors: common.js does this based on a naming convention. For each key in $json['error'], it looks for two elements, replacing underscores in the key with hyphens:
#input-{ключ}receives theis-invalidclass and a red border;#error-{ключ}receives the error text and thed-blockclass, that is, it becomes visible.
The warning key is shown separately, as a general message in the #alert block. The $json['success'] also appears there. If the JSON contains redirect, the script navigates to that address. Old error markers are cleared before each submission.
Example
<div class="mb-3">
<label for="input-title" class="form-label">{{ entry_title }}</label>
<input type="text" name="module_mymodule_title" value="{{ module_mymodule_title }}" id="input-title" class="form-control"/>
<div id="error-title" class="invalid-feedback"></div>
</div>
This leads to a typical mistake: the $json['error']['title'] key is present, but in the template the field has id="input-module-title". The form will not save, and the user will not understand why, because the error will not appear anywhere. Keep the error key, the id of the field, and the id of the error block in sync.
Another useful behavior: for each top-level key in the JSON, common.js writes the value into the form field with the same name (name). The built-in html module uses this: after the first save of a new instance, save() returns $json['module_id'], and the hidden module_id field receives the ID. The next click on "Save" then edits this instance instead of creating another one.
How do you make multilingual fields?
Texts that the customer sees (block title, description, button label) are stored separately for each language. The language list is provided by $this and getLanguages(). The template builds tabs by language, and field names become arrays with language_id: module_description[{{ language.language_id }}][title].
- Saving. The array goes into
settingor into themoduletable as JSON and is returned as an array, so nothing needs to be parsed manually. - Errors. For language fields in 4.1, the error key is formed from the name and
language_id, as in the core information pages form:$json['error']['title_' . $language_id]and theid="error-title-{{ language.language_id }}"block. - Language flags. OpenCart 3.0: the image path is built in the template:
language/. OpenCart 4.1: the ready-made path{{ language.code }}/ {{ language.code }}.png language.imageis already added by thelocalisation/model.language - New language. After a language is added to the store, there are no values for it yet. In the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary →, always check whether the
config_language_idkey exists in the array and have a fallback.
Field labels and error messages should themselves live in the module's language files, not in the template. How to organize them is described in the article module language files.
Module settings or instances: where to store the form?
Which model the handler calls depends on where the POST goes.
| Scenario | Model and method | Example in core |
|---|---|---|
| One setting for the entire store | setting/setting → editSetting('module_{код}', $data) | account |
| Several blocks with different settings | setting/module → addModule() / editModule($module_id, $data) | html, featured, banner |
The module code in addModule() differs between versions. OpenCart 3.0: addModule('html', $data). OpenCart 4.1: together with the extension folder: addModule('opencart.html', $data). For an instance in the form, the name field is required, which is later visible in the modules list and in "Design → Layouts". Built-in modules check its length, which must be from 3 to 64 characters.
For a form with editSetting(), keep in mind two rules described in the article model setting and the setting table: the method first deletes the entire group, and silently discards fields without the code prefix. Therefore, all form fields must be in one form and have names with the module_{код}_ prefix.
Which small details break the form most often?
- Checkbox without a hidden field. An unchecked checkbox is not sent in the POST. Then, when the form is redisplayed after an error, the 3.0 controller takes the old value from config, and the checkbox becomes checked again. In 4.1, the built-in templates place an
<input type="hidden" name="..." value="0"/before the checkbox, so the POST always contains a value.> - Numbers without type casting. A "minimum amount" field arrives as a string, including with a comma, such as
"150,50". Validateis_numeric()and save the normalized value. - HTML in text fields. The Request class in both versions passes
$thisthrough->request ->post htmlspecialchars(..., ENT_COMPAT, 'UTF-8'), so HTML reaches the database already escaped. For fields with a visual editor, decode on output in the storefront usinghtml_entity_decode(), as the built-inhtmlmodule does. Output plain texts without decoding. - Links without
user_token. Thesaveaddresses, "Back", and any AJAX addresses of the form must contain the token, otherwise the admin will redirect to the login page. More about this in the article user_token in the admin. - A form split across several
formtags. In 4.1, the "Save" button submits only the form withid="form-module". Fields located in another form or outside it will not be saved, andeditSetting()will also delete their old values.
Summary
- OpenCart 3.0: one
index()method, validation invalidate(), errors in$this->error, redirect after success. - OpenCart 4.1: a separate
save(), the response in JSON, and errors are shown bycommon.jsbased on the#input-{ключ}and#error-{ключ}convention. - Always check permissions with
modifyfirst, measure strings with UTF-8 in mind, and duplicate all checks on the server. - Store global settings via
editSetting(), and make blocks with different settings into instances viasetting/module.
The step-by-step first module will help you put everything together into a working module. The remaining topics of the section are collected on the page creating extensions for OpenCart.