Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 27 ยท The admin side

Admin Settings Forms

Build an OpenCart 4 extension settings page: the form controller, module_ config keys, editSetting, AJAX save, validation and the modify permission check.

Almost every extension needs a settings page. A payment method needs an API key and a minimum order total, a module needs a status switch, a shipping method needs a rate table. In OpenCart 4 this page is a normal admin controller with two jobs: show the form with the current values, and save what the merchant typed, after checking that the merchant is allowed to and that the values make sense.

This lesson walks through the pieces: the controller with its index and save methods, the module_ and payment_ key prefixes that decide what gets stored, the setting/setting model, the AJAX save that OpenCart 4 uses, and the checks you must never skip. The OpenCart code itself cannot run on this site, so it is shown read-only. The runnable examples are plain-PHP stand-ins on SQLite that follow the same rules. If routes or the registry are new to you, read Routing and Controllers and Models, the Registry and the Database first.

Where the files live

An OpenCart 4 extension keeps its admin code under extension/<vendor>/admin/. For a module called hello from vendor acme you would have:

TEXT
extension/acme/admin/controller/module/hello.php
extension/acme/admin/language/en-gb/module/hello.php
extension/acme/admin/view/template/module/hello.twig

The route of the settings page is extension/acme/module/hello. The first two parts after extension/ are the vendor folder and the type folder; the last part is the file name. The class is Opencart\Admin\Controller\Extension\Acme\Module\Hello. See Anatomy of an Extension for the full layout.

The controller: index shows, save stores

Here is a typical settings controller. It is read-only here because it needs a running OpenCart.

PHP
<?php
namespace Opencart\Admin\Controller\Extension\Acme\Module;

class Hello extends \Opencart\System\Engine\Controller {
    public function index(): void {
        $this->load->language('extension/acme/module/hello');
        $this->document->setTitle($this->language->get('heading_title'));

        $data['breadcrumbs'] = [];
        // ... dashboard / extensions / this page links, each with user_token ...

        $data['save'] = $this->url->link('extension/acme/module/hello.save', 'user_token=' . $this->session->data['user_token']);
        $data['back'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module');

        $data['module_hello_status'] = $this->config->get('module_hello_status');
        $data['module_hello_greeting'] = $this->config->get('module_hello_greeting');

        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');

        $this->response->setOutput($this->load->view('extension/acme/module/hello', $data));
    }

    public function save(): void {
        $this->load->language('extension/acme/module/hello');
        $json = [];

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

        $greeting = trim((string)($this->request->post['module_hello_greeting'] ?? ''));
        if (oc_strlen($greeting) < 3 || oc_strlen($greeting) > 64) {
            $json['error']['greeting'] = $this->language->get('error_greeting');
        }

        if (!$json) {
            $this->load->model('setting/setting');
            $this->model_setting_setting->editSetting('module_hello', $this->request->post);
            $json['success'] = $this->language->get('text_success');
        }

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

A few details are worth slowing down for.

The method separator. The save URL ends in .save. In OpenCart 4.0.0 and 4.0.1 the separator between route and method was a pipe (hello|save); from 4.0.2 it is a dot. Check which your target version uses before you copy any snippet, and read the core controllers of that version as your reference.

The user_token. Every admin URL carries the session's user_token. Without it the admin refuses the request. That is also a basic CSRF defence, which we revisit in Security for Extension Developers.

Why save is separate from index. OpenCart 3 posted the form to index and reloaded the page. OpenCart 4 submits the form with AJAX to a save method that answers with JSON. The page does not reload, errors appear next to the fields, and the merchant keeps their scroll position.

sequenceDiagram
    participant M as Merchant
    participant J as common.js
    participant C as save()
    participant S as setting table
    M->>J: Click Save
    J->>C: POST form + user_token
    C->>C: Permission check, then validation
    alt errors found
        C-->>J: {"error": {"greeting": "..."}}
        J-->>M: Red text under the field
    else all fine
        C->>S: editSetting('module_hello', post)
        C-->>J: {"success": "..."}
        J-->>M: Green alert
    end

The browser script sends the form, and the controller answers only with JSON. Nothing is written until both checks pass.

How the AJAX save is wired

In the Twig template you mark the form so the shared admin script takes over. The pattern in OpenCart 4 is a form with data-oc-toggle="ajax" and a button that points at it:

TWIG
<form id="form-module" action="{{ save }}" method="post" data-oc-toggle="ajax">
  <div class="mb-3">
    <label for="input-greeting" class="form-label">{{ entry_greeting }}</label>
    <input type="text" name="module_hello_greeting" value="{{ module_hello_greeting }}" id="input-greeting" class="form-control"/>
    <div id="error-greeting" class="invalid-feedback"></div>
  </div>
  <div class="form-check form-switch form-switch-lg">
    <input type="hidden" name="module_hello_status" value="0"/>
    <input type="checkbox" name="module_hello_status" value="1" id="input-status" class="form-check-input"{% if module_hello_status %} checked{% endif %}/>
    <label for="input-status" class="form-check-label">{{ entry_status }}</label>
  </div>
</form>
<button type="submit" form="form-module" class="btn btn-primary">{{ button_save }}</button>

When the JSON comes back with error, the script puts each message into the element whose id is error- plus the key (error-greeting) and marks the input invalid. A key called warning shows a general alert at the top. If you invent your own error keys, give the form matching error-... containers, or the message has nowhere to appear. The hidden input before the checkbox is a common trick: an unchecked checkbox sends nothing, so the hidden 0 guarantees the status key always arrives.

Config keys and the prefix rule

Settings live in the setting table as rows of store_id, code, key, value and serialized. For extensions, OpenCart expects the key to start with the type and the extension name: module_hello_status, payment_gateway_total, shipping_weight_rate. The code is the shared start of those keys, here module_hello.

The model call is editSetting($code, $data, $store_id = 0). It first deletes all rows with that code for that store, then inserts every entry of $data whose key starts with the code. Other keys are silently ignored. This is a safety feature (the form also posts nothing but your fields, yet a tampered post cannot write to unrelated settings), and it is also a classic bug: if your field is named hello_status instead of module_hello_status, it simply never gets saved, and no error tells you why. Arrays are stored as JSON with serialized set to 1 and come back as arrays from $this->config->get().

Also note that editSetting replaces the whole group. If your form does not post a key, the old row is gone. Post every key the page manages, and nothing else will be disturbed.

The standard fields almost every extension has are:

Key Purpose
<type>_<name>_status 1 enables the extension, 0 disables it
<type>_<name>_sort_order Position among siblings, ascending
<type>_<name>_geo_zone_id Payment or shipping only; 0 means all zones

The extension must also be enabled by status for the storefront to use it. Payment, shipping and total types additionally appear in the extension list only after the Install button created their permission rows, which is covered in Install, Uninstall and Permissions.

The two checks you never skip

Permission. The admin menu hides pages the user group cannot access, but hiding is not protection. Inside save call $this->user->hasPermission('modify', $route) and refuse with an error when it returns false. A user with only the access permission can open the page and read it, but must not be able to change it. Without the check, anyone with a login who can guess the URL can write settings.

Validation. Everything in $this->request->post came from the browser. Check length, type and allowed values before saving, and return messages from the language file rather than hard-coded text so the page can be translated. Cast numbers ((int), (float)), validate a status is 0 or 1, and for URLs or API keys check a sensible pattern. When validation finds problems, do not call editSetting at all.

Try it: a settings form on SQLite

This stand-in is not OpenCart. It imitates three real ideas: the setting table, the delete-then-insert behaviour with the key prefix rule, and the save() flow of permission check, validation and a JSON answer.

PHP A save() flow with permission and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Only the third case reaches the database. The first is stopped by the permission check, the second by validation; both return JSON with an error object and write nothing, exactly as the real controller must.

The next example shows the prefix rule and arrays. A stray field is dropped without any message, a list is stored as JSON, and a second save replaces the group completely.

PHP The prefix rule and serialized arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

After the second save the cities list is gone, because the group is deleted before inserting. Real forms post all of their fields every time, which is why the hidden-input trick for checkboxes matters.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to a posted key that does not start with the code passed to editSetting?

    editSetting only inserts keys that start with the code, such as module_hello_status for the code module_hello. Other keys are dropped without any error, which is a common cause of settings that never save.
  2. 2. Why must save() call hasPermission('modify', ...) even though the menu hides the page?

    A hidden link is not access control. The server must refuse the write itself, otherwise any logged-in admin user who knows the route could change the settings.
  3. 3. In OpenCart 4, how does the settings form normally report validation errors?

    The shared admin script sends the form by AJAX. A JSON answer with error keys is shown under matching fields (error-<key>), while success shows an alert.
  4. 4. Why is a hidden input with value 0 placed before a status checkbox?

    Browsers omit unchecked checkboxes from the post. Since editSetting replaces the whole group, a missing status key would delete the row; the hidden 0 prevents that.

Summary

  • A settings page is an admin controller with index (renders the form) and save (AJAX, answers with JSON).
  • Store values under keys that start with the type and extension name, such as module_hello_status or payment_gateway_total.
  • editSetting($code, $data) deletes the group, then inserts only keys that start with the code; arrays are stored as JSON.
  • Always check hasPermission('modify', ...) and validate every posted value before saving.
  • Return errors as $json['error'][field] with matching error-<field> elements in the Twig template.
  • Check the method separator (| or .) for the OpenCart 4.0.x version you target.

Next, see how the extension creates its tables and permissions in Install, Uninstall and Permissions.