No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
Building extensions

OpenCart Module Settings: model setting and setting Table in 3.0 and 4.1

How an OpenCart Module Stores and Reads Its Settings: the setting Table, model setting/setting Methods, Key Prefixes and editSetting Pitfalls.

9 min read OC 3.0 OC 4.1

The standard OpenCart module stores its settings in the setting table through the setting/setting model. No custom tables or migrations are needed for this. The admin form submits fields with the module code prefix, editSetting() overwrites them in one batch, and at startup the core loads all rows into $this->config, from which both the admin and the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → read them. Below is how this works in OpenCart 3.0 and 4.1 and where data gets lost in this scheme. Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

How is the setting table structured?

The table structure is the same in both versions: setting_id, store_id, code, key, value, serialized. The value column is of type text (up to 64 KB) in both branches.

ColumnWhat it storesExample
store_idStore; 0 means the default store0
codeSettings group used by editSetting()module_account
keyName under which the value will end up in configmodule_account_status
valueString or JSON1
serializedFlag indicating that value is a JSON array0

The code column should be understood as the "owner" of the rows. For store settings, this is config, and for extensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → it consists of the type and code: payment_cod, shipping_flat, module_account. The core relies on this convention. For example, when an extension is uninstalled, it deletes all rows with code = {тип}_{код} for all stores (all store_id) in both branches: in 4.1 this is done by deleteSettingsByCode(), in 3.0 by model_setting_extension->uninstall. Only settings saved under a different code will remain as garbage in the database.

The key column must be globally unique within a store, although there is no index on it. The core merges all rows into one flat config, so identical keys from two modules will overwrite each other without any error. Hence the rule: every key starts with the owner code, for example module_mymodule_title, not just title. How extension types form these prefixes is explained in the article OpenCart module types.

How does a module save settings via editSetting?

In the admin, the module loads $this->load->model('setting/setting') and passes the entire form POST to editSetting($code, $data, $store_id). Here is how this method looks in 3.0:

admin/model/setting/setting.php · OpenCart 3.0.5.1 · lines 19–31

	public function editSetting($code, $data, $store_id = 0) {
		$this->db->query("DELETE FROM `" . DB_PREFIX . "setting` WHERE store_id = '" . (int)$store_id . "' AND `code` = '" . $this->db->escape($code) . "'");

		foreach ($data as $key => $value) {
			if (substr($key, 0, strlen($code)) == $code) {
				if (!is_array($value)) {
					$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'");
				} else {
					$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(json_encode($value, true)) . "', serialized = '1'");
				}
			}
		}
	}

Three rules follow from this code, which you should know by heart:

  1. Everything is deleted first. The method removes all rows with this code and store_id, then inserts only what arrived in $data. Saving half of the form means losing the other half.
  2. Keys without the prefix are silently discarded. Only fields whose names start with $code are saved. The title field in the module form module_mymodule will not be saved, and you will see no error.
  3. Arrays become JSON. For an array, serialized = 1 is set, and when reading, the value is decoded back into an array. This is how multilingual fields, product lists, and settings per customer groupA segment of buyers (retail, wholesale) with different prices and terms. More in the glossary → are stored.

OpenCart 4.1: the logic is the same, but the code is shorter. The method is typed as editSetting(string $code, array $data, int $store_id = 0): void, deletion is moved into deleteSetting(), and insertion is done in a single query:

admin/model/setting/setting.php · OpenCart 4.1.0.4 · lines 77–85

	public function editSetting(string $code, array $data, int $store_id = 0): void {
		$this->deleteSetting($code, $store_id);

		foreach ($data as $key => $value) {
			if (substr($key, 0, strlen($code)) == $code) {
				$this->db->query("INSERT INTO `" . DB_PREFIX . "setting` SET `store_id` = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(!is_array($value) ? $value : json_encode($value)) . "', `serialized` = '" . (bool)is_array($value) . "'");
			}
		}
	}

What does this look like in the module controller?

The easiest way to see it is in the standard account module, which exists in both versions. Its module_account_status key and module_account code clearly show what the prefix should look like.

OpenCart 3.0: the form is submitted via a regular POST to the same route. The index() method, after checking permissions, calls editSetting('module_account', $this->request->post), puts the message in the session, and redirects. For the form values, the controllerCode that receives a request and prepares data. More in the glossary → takes data from POST if the form returned with an error, and otherwise from $this->config->get('module_account_status').

OpenCart 4.1: the form has the data-oc-toggle="ajax" attributeA product characteristic that does not affect the price: material, weight, power. It is set in "Catalog → Attributes" and displayed on the "Specification" tab. More in the glossary → and is submitted via an AJAX request to a separate save() method at the extension/opencart/module/account.save route. The method returns JSON with success or error, and the page does not reload. For the status checkbox, the template places a hidden field with value="0" right before the checkbox itself, so a disabled status also gets into the POST.

Example

public function save(): void {
	$this->load->language('extension/mymodule/module/mymodule');

	$json = [];

	if (!$this->user->hasPermission('modify', 'extension/mymodule/module/mymodule')) {
		$json['error'] = $this->language->get('error_permission');
	}

	if (!$json) {
		$this->load->model('setting/setting');

		$this->model_setting_setting->editSetting('module_mymodule', $this->request->post);

		$json['success'] = $this->language->get('text_success');
	}

	$this->response->addHeader('Content-Type: application/json');
	$this->response->setOutput(json_encode($json));
}

Field validation, error messages next to each field, and checkbox handling are best moved into a separate settings form topic. For JSON responses and JS-side processing, read the article AJAX responses from controllers. The modify permissions are covered in the article module access permissions.

Extensions → Extensions, extension type 'Modules': the edit button opens the module settings form
Extensions → Extensions, extension type "Modules": the edit button opens the module settings form · OpenCart 4.1.0.4

How do settings get into $this->config?

You do not need to read settings through the model in every controller. At the start of each request, the core selects the setting rows and calls $this->config->set($key, $value), and for rows with serialized = 1 it first runs json_decode($value, true).

flowchart TD
  A["Request to index.php"] --> B["startup: select setting rows"]
  B --> C{"serialized = 1?"}
  C -- "yes" --> D["json_decode into array"]
  C -- "no" --> E["value as is"]
  D --> F["config->set(key, value)"]
  E --> F
  F --> G["Controller: config->get('module_..._status')"]
  • Storefront, OpenCart 3.0: the startup/startup controller selects rows with store_id = 0 and the current store, sorted by store_id. This way, store-specific values override the default ones.
  • Storefront, OpenCart 4.1: the same is done by a separate startup/setting controller through the model method getSettings($store_id).
  • Admin, both versions: only store_id = 0 settings are loaded.

The practical conclusion: in a storefront controller, write $this->config->get('module_mymodule_status'), not a separate SQL query. The values are already in memory, and an extra database query gives nothing. For more details on file-based configs and their relation to the database, see the article config.php and settings in the database.

Which other setting model methods will be useful?

Besides editSetting(), the model has several methods for point operations. Their names differ between versions, so code ported from 3.0 to 4.1 often fails with an error about a non-existent method.

TaskOpenCart 3.0OpenCart 4.1
All keys of a group as an arraygetSetting($code, $store_id = 0)getSetting(string $code, int $store_id = 0): array
One value by keygetSettingValue($key, $store_id = 0), returns null if the key does not existgetValue(string $key, int $store_id = 0): string, returns ''
Update one valueeditSettingValue($code, $key, $value, $store_id)editValue($code, $key, $value, $store_id)
Delete a group in a storedeleteSetting($code, $store_id = 0)deleteSetting(string $code, int $store_id = 0)
Delete a group in all storesnonedeleteSettingsByCode(string $code)

One detail is easy to miss: editSettingValue() and editValue() perform UPDATE, not an insert. If a row with such code and key does not exist yet, for example because the module has just been installed, the update will change nothing. For service values such as the last sync date or an API token, first make sure the row is created, for example in the install method via editSetting().

The storefront has its own setting/setting model with the same read methods. OpenCart 3.0: these are getSetting() and getSettingValue(). OpenCart 4.1: getSettings(), getSetting(), and getValue(). The storefront has no write methods, and that is correct: the storefront should not change settings.

What about multi-store setups and large data?

If a module must behave differently in different stores, pass the third argument: editSetting('module_mymodule', $data, $store_id). For the form, this means a store dropdown and loading values through getSetting('module_mymodule', $store_id) rather than $this->config. The admin keeps only the default store in config, so values of other stores cannot be read through config. In the storefront, the core itself overlays the store values on top of the default ones.

The setting table is well suited for configuration but not for data. Signs that a module needs its own table:

  • the value grows with the catalog: product bindings, logs, API response cache;
  • you need to search or sort by a field inside the value;
  • data changes while the storefront is running, not only when the form is saved;
  • JSON in value reaches hundreds of kilobytes. It gets decoded on every request to every page, because the core loads all settings at once.

The last point matters for performance: each large serialized key slows down every store page. Keep switches, texts, identifiers, and small arrays in setting, and move everything else into the module's tables.

Summary

  • Module settings live in setting under the code {тип}_{код}, and every key starts with this code.
  • editSetting() first deletes the entire group, then writes only keys with the correct prefix. Always pass it the full form.
  • Arrays are stored as JSON with serialized = 1 and returned as arrays in $this->config.
  • In code, read values via $this->config->get(), and use the model for other stores and point changes.
  • In 4.1, methods have been renamed (getValue, editValue) and typed: check these when porting a module from 3.0.

Next, build a complete module following the step-by-step example of your first module. The rest of the extension topics are collected on the page creating extensions for OpenCart.

FAQ

Can you save module settings with a direct SQL query, without a model?
Yes, but then you are responsible for code, serialized and JSON yourself. The model does this the same way as the core, so a direct query is justified only in migrations.
Why didn't the settings change on the storefront after saving the form?
Most often the form field has no code prefix, so editSetting dropped it. The second reason is that the value was saved for a different store_id than the one the storefront uses.
Will the settings disappear when the module is updated?
No, as long as the module is not removed. Keys are deleted only when the extension is uninstalled in the admin or by the module's own uninstall method.
Where should a module's password or API key be stored?
Usually in setting, like the rest of the settings, since there are no other built-in storage options. Don't output it on the storefront or write it to logs, and restrict access to the form with the modify permission.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.