# OpenCart Module Settings Form: Validation and Saving in 3.0 and 4.1

> How to build a module settings form in the OpenCart admin: POST and validate() in 3.0, AJAX save() method with JSON errors in 4.1, multilingual fields and instances.

Джерело: https://opencartcode.com/en/wiki/dev-extensions/module-settings-form-opencart
OpenCart: 3.0, 4.1
Оновлено: 2026-11-24

The module settings form in OpenCart consists of three parts: the [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller) 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:

1. If the request method is `POST` and `validate()` returns `true`, the controller saves the data, puts `text_success` into `$this->session->data['success']`, and performs `$this->response->redirect()` to the [extensions](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#extensions) list with `&type=module`.
2. Otherwise, the controller collects data for the template. Errors from `$this->error` are placed into the `error_warning`, `error_name` variables, 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.
3. The template shows `error_warning` as a general message at the top, and the field error in an `<div class="text-danger">` block below it.

Example

```php
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](https://opencartcode.com/en/wiki/dev-mvc/opencart-controller).

## 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->url->link('extension/mymodule/module/mymodule.save', 'user_token=...')`. The form tag has the `data-oc-toggle="ajax"` attribute, and the general admin script `admin/view/javascript/common.js` 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 file](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#language-file) and sets the page title. Then it builds the [breadcrumbs](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#breadcrumbs) ("Home" → "Extensions" → module name) and the `save` and `back` addresses, where the "Back" button leads to `marketplace/extension` with `&type=module`. It takes field values directly from `$this->config->get('module_mymodule_title')`, 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/json` header:

Example

```php
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->request->post + $required` 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](https://opencartcode.com/en/wiki/dev-mvc/ajax-opencart).

Extensions → Extensions (Розширення → Розширення), type "Modules": this is where the module settings form is opened · OpenCart 4.1.0.4

## 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 the `is-invalid` class and a red border;
- `#error-{ключ}` receives the error text and the `d-block` class, 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

```twig
<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->load->model('localisation/language')` 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 `setting` or into the `module` table 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 the `id="error-title-{{ language.language_id }}"` block.
- **Language flags.** **OpenCart 3.0:** the image path is built in the template: `language/{{ language.code }}/{{ language.code }}.png`. **OpenCart 4.1:** the ready-made path `language.image` is already added by the `localisation/language` model.
- **New language.** After a language is added to the store, there are no values for it yet. In the [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront), always check whether the `config_language_id` key 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](https://opencartcode.com/en/wiki/dev-mvc/opencart-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](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-setting): 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"`. Validate `is_numeric()` and save the normalized value.
- **HTML in text fields.** The Request class in both versions passes `$this->request->post` through `htmlspecialchars(..., ENT_COMPAT, 'UTF-8')`, so HTML reaches the database already escaped. For fields with a visual editor, decode on output in the storefront using `html_entity_decode()`, as the built-in `html` module does. Output plain texts without decoding.
- **Links without `user_token`.** The `save` addresses, "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](https://opencartcode.com/en/wiki/dev-mvc/opencart-user-token).
- **A form split across several `form` tags.** In 4.1, the "Save" button submits only the form with `id="form-module"`. Fields located in another form or outside it will not be saved, and `editSetting()` will also delete their old values.

> Do not rely only on HTML attributes such as `required` or `maxlength`. A request to `save()` can be sent directly, so repeat every check on the server.

## Summary

- OpenCart 3.0: one `index()` method, validation in `validate()`, errors in `$this->error`, redirect after success.
- OpenCart 4.1: a separate `save()`, the response in JSON, and errors are shown by `common.js` based on the `#input-{ключ}` and `#error-{ключ}` convention.
- Always check permissions with `modify` first, 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 via `setting/module`.

The [step-by-step first module](https://opencartcode.com/en/wiki/dev-extensions/how-to-create-an-opencart-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](https://opencartcode.com/en/wiki/dev-extensions).

## FAQ

**Can you make a form without AJAX in 4.1, as in 3.0?**

You can remove data-oc-toggle and handle POST in index(), but then you'll have to show errors and messages yourself. The standard save() approach is shorter and consistent with the rest of the admin.

**How do I add a file or image upload to the form?**

For images, use the built-in admin image manager, which writes the path to a hidden field. For arbitrary files, it's better to upload them with a separate AJAX method and store only the path in the settings.

**How do I validate a field depending on another one, for example an API key only when the status is enabled?**

In validate() or save(), check the condition value first, then the dependent field. Return the error with the dependent field's key so it appears next to that field.

**Can I verify a service's API key right during saving?**

Yes, but a request to an external API inside save() slows down saving and fails when the service is unavailable. It's more convenient to add a separate "Test connection" button with its own AJAX method.
