# How to Create an OpenCart Module from Scratch: Your First Module for 3.0 and 4.1

> Step by step, we build the simplest OpenCart module: admin and storefront files, language strings, saving settings, installation, and output on the page in 3.0 and 4.1.

Джерело: https://opencartcode.com/en/wiki/dev-extensions/how-to-create-an-opencart-module
OpenCart: 3.0, 4.1
Оновлено: 2026-11-25

To create an OpenCart module, you need two controllers: one in the admin for the settings form and one on the [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) for the output. They are accompanied by language files and Twig templates, placed according to strict path rules. Then the module is installed in [Extensions](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#extensions) → Extensions with the "Modules" type selected and added to a page layout. Below is a complete working example of the `hello` module, which displays text from its settings on the site. The code is given for OpenCart 3.0 and 4.1, and the differences between the versions are noted separately. The examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

## What does a module consist of, and how do 3.0 and 4.1 differ?

In OpenCart terms, a "module" is one of the extension types, alongside payment, shipping, [order totals](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#order-totals), feeds, and reports. A module outputs a block into a layout position: the left or right column, or the top or bottom of the content. That makes this type the most convenient for a first extension. It does not interfere with the checkout, and the result is visible on the page right away.

The main difference between the versions lies in file placement. **OpenCart 3.0:** extension files live inside the core, in the `extension/module/` subdirectories of the admin and catalog. **OpenCart 4.1:** each extension lives in its own `extension/<код>/` folder in the site root. The core loads classes by namespace. A detailed directory map is in the article about [OpenCart file structure](https://opencartcode.com/en/wiki/dev-architecture/opencart-file-structure).

| File | OpenCart 3.0 | OpenCart 4.1 |
| --- | --- | --- |
| Admin controller | `admin/controller/extension/module/hello.php` | `extension/hello/admin/controller/module/hello.php` |
| Admin language | `admin/language/en-gb/extension/module/hello.php` | `extension/hello/admin/language/en-gb/module/hello.php` |
| Admin template | `admin/view/template/extension/module/hello.twig` | `extension/hello/admin/view/template/module/hello.twig` |
| Storefront controller | `catalog/controller/extension/module/hello.php` | `extension/hello/catalog/controller/module/hello.php` |
| Storefront template | `catalog/view/theme/default/template/extension/module/hello.twig` | `extension/hello/catalog/view/template/module/hello.twig` |
| Admin route | `extension/module/hello` | `extension/hello/module/hello` |

The file path is also the route. The core looks up the [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller) by the value of `route=`, so a single mistake in a folder name and the module "disappears". How the core parses the route is explained in the article about [route= routing in 3.0 and 4.1](https://opencartcode.com/en/wiki/dev-mvc/opencart-route).

## How do you write the admin part in OpenCart 3.0?

The admin controller performs three tasks. It displays the form, checks the permission to make changes, and saves the settings to the `setting` table. The simplest variant is a single-instance module. All its settings have the `module_hello_` prefix, and the enable switch is defined by the `module_hello_status` key. This prefix is mandatory: the storefront in 3.0 checks exactly `module_<код>_status` when it decides whether to output the module in a layout.

### Language file

Example

```php
<?php
// admin/language/en-gb/extension/module/hello.php
$_['heading_title']    = 'Hello — привітання';
$_['text_extension']   = 'Розширення';
$_['text_edit']        = 'Налаштування модуля';
$_['text_success']     = 'Налаштування збережено!';
$_['entry_text']       = 'Текст привітання';
$_['entry_status']     = 'Статус';
$_['error_permission'] = 'У вас немає прав змінювати цей модуль!';
```

The `heading_title` string is required, because the module name in the extensions list is taken from it. If the admin is in Ukrainian, place a copy of the file in the `uk-ua` language directory. In 3.0 the core first loads `en-gb` and then the active language on top of it, so missing keys remain in English. In 4.1 only the active language is loaded, with no fallback to `en-gb`. Therefore the file must be in the `uk-ua` directory, otherwise the interface will show key names instead of strings, for example `heading_title`. Translation details are described in the article about [module language files](https://opencartcode.com/en/wiki/dev-mvc/opencart-language-files).

### Controller

Example

```php
<?php
class ControllerExtensionModuleHello extends Controller {
    private $error = array();

    public function index() {
        $this->load->language('extension/module/hello');
        $this->document->setTitle($this->language->get('heading_title'));
        $this->load->model('setting/setting');

        if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) {
            $this->model_setting_setting->editSetting('module_hello', $this->request->post);
            $this->session->data['success'] = $this->language->get('text_success');
            $this->response->redirect($this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true));
        }

        $data['error_warning'] = isset($this->error['warning']) ? $this->error['warning'] : '';
        $data['action'] = $this->url->link('extension/module/hello', 'user_token=' . $this->session->data['user_token'], true);
        $data['cancel'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true);

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

        $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/module/hello', $data));
    }

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

The class name is built from the route. Slashes are removed, segments are capitalized, and underscores disappear. The route `extension/module/hello_world` yields the class `ControllerExtensionModuleHelloWorld`. The `user_token` parameter in every link is mandatory: without it, the admin throws you to the login page. Why this is so is explained in the article about [user_token and admin security](https://opencartcode.com/en/wiki/dev-mvc/opencart-user-token). The core automatically passes strings from the [language file](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#language-file) to the template, so in Twig you can write `{{ heading_title }}` right away.

## What changes in the OpenCart 4.1 admin?

The logic in 4.1 is the same, but three things have changed: the namespace, the base class, and the way data is saved. The form is now submitted via an AJAX request to a separate `save()` method, which returns JSON. There is no redirect after saving; the message is shown by the admin JavaScript.

Example

```php
<?php
namespace Opencart\Admin\Controller\Extension\Hello\Module;

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

        $data['save'] = $this->url->link('extension/hello/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_text']   = $this->config->get('module_hello_text');
        $data['module_hello_status'] = $this->config->get('module_hello_status');

        $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/hello/module/hello', $data));
    }

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

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

        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));
    }
}
```

The namespace is built from the path: `Extension\Hello\Module` corresponds to the `extension/hello/admin/controller/module/` folder. If the extension folder is named `hello_world`, the namespace segment will be `HelloWorld`. In 4.1 the method is separated by a dot (`hello.save`). The core automatically replaces the old `|` separator with a dot.

In the template, it is enough to mark the form with the `data-oc-toggle="ajax"` attribute. The admin script will submit it itself to `action` and show `success` or `error`.

Example

```twig
<form id="form-module" action="{{ save }}" method="post" data-oc-toggle="ajax">
  <div class="mb-3">
    <label for="input-text" class="form-label">{{ entry_text }}</label>
    <input type="text" name="module_hello_text" value="{{ module_hello_text }}" id="input-text" class="form-control"/>
  </div>
  <div class="form-check form-switch">
    <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>
```

The hidden input with the value `0` before the checkbox is needed deliberately. Without it, a disabled switch would not be sent in the POST at all, and `editSetting()` would remove the status key. The general scheme of JSON responses is covered in the article about [AJAX in OpenCart controllers](https://opencartcode.com/en/wiki/dev-mvc/ajax-opencart).

## How do you display the module on the storefront?

On the storefront, the module controller does not return a full page. It returns a fragment of HTML, which the core inserts into a layout position. That is why the `index()` method ends with `return $this->load->view(...)` rather than `setOutput()`.

OpenCart 3.0

OpenCart 4.1

Example: OpenCart 3.0

```php
<?php
// catalog/controller/extension/module/hello.php
class ControllerExtensionModuleHello extends Controller {
    public function index() {
        $this->load->language('extension/module/hello');
        $data['text'] = $this->config->get('module_hello_text');

        return $this->load->view('extension/module/hello', $data);
    }
}
```

Example: OpenCart 4.1

```php
<?php
namespace Opencart\Catalog\Controller\Extension\Hello\Module;

class Hello extends \Opencart\System\Engine\Controller {
    public function index(): string {
        $this->load->language('extension/hello/module/hello');
        $data['text'] = $this->config->get('module_hello_text');

        return $this->load->view('extension/hello/module/hello', $data);
    }
}
```

The storefront template can be minimal, for example `<div class="hello-module">{{ text }}</div>`. **OpenCart 3.0:** the template goes into `catalog/view/theme/default/template/extension/module/`. If the active third-party theme has no copy of its own, the core will take the file from `default`. **OpenCart 4.1:** the template lives inside the extension folder, and the theme can override it via Design → Theme Editor. The syntax and filters are described in the reference on [Twig in OpenCart](https://opencartcode.com/en/wiki/dev-mvc/opencart-twig-templates).

The `module_hello_text` key here is the same for all languages. For a bilingual store, store an array under `language_id` and on the storefront take the value by `$this->config->get('config_language_id')`. The Request class already passes POST data through `htmlspecialchars`, so plain text is safe to output in the template.

## How do you install the module and add it to a page?

Files in the right folders are only half the work. Until the module is installed, it is absent from the `extension` table, and the user group has no rights to its route. So even the administrator will get "no access". The procedure is as follows:

1. **OpenCart 3.0:** upload the files to the server or pack them into an `hello.ocmod.zip` archive with the `upload/` folder inside and upload it via Extensions → Installer. **OpenCart 4.1:** the `hello.ocmod.zip` archive contains `install.json`, `admin/`, and `catalog/` in its root, without `upload/`. After uploading, click "Install" next to the entry in the list, and the files will be extracted into `extension/hello/`.
2. Open Extensions → Extensions, select the "Modules" type, and click "Install" next to your module. At this step the core creates a record in the `extension` table, grants your group the `access` and `modify` rights, and calls the `install()` method of the controller, if it exists.
3. Click "Edit", enter the text, enable the status, and save.
4. In Design → Layouts, open, for example, the "Home" layout, add the module to the desired position, and save.

Extension installer: uploaded hello.ocmod.zip and the «Install» button · OpenCart 4.1.0.4

A minimal `install.json` for 4.1 looks like this:

Example

```js
{
  "name": "Hello — привітання",
  "version": "1.0.0",
  "author": "Ваше ім'я",
  "link": "https://example.com"
}
```

Extensions → Extensions, «Modules» type: the Hello module in the list, with «Install» and «Edit» buttons · OpenCart 4.1.0.4

The storefront decides whether to show the module in position controllers such as `common/column_left`. They read the layout's modules, and for single-instance ones they check `module_hello_status` in the config. The whole path from installation to display looks like this:

```mermaid
flowchart TD
A["Files in the extension folder"] --> B["Extension installer"]
B --> C["Extensions → Extensions, Modules type: Install"]
C --> D["Record in extension and group permissions"]
D --> E["Form: editSetting module_hello"]
E --> F["Layout: module in position"]
F --> G["column_left checks status"]
G --> H["load->controller returns HTML"]
```

Design → Layouts: the Hello module added to a column position · OpenCart 4.1.0.4

## Why doesn't the module appear: typical mistakes of a first extension

Almost all problems with a first module come down to mismatched names or a skipped installation step. Before looking for complex causes, go through this list:

- **The module is not in the extensions list.** Wrong folder or controller file name: the extensions list is built from files in the controller directory. In 4.1, the cause is often also an archive with `upload/` inside: then the files end up in `extension/hello/upload/`. If the language file lacks `heading_title`, the module will be in the list, but its key `heading_title` will be shown instead of its name.
- **"No access" after installation.** The module was installed under a different group, or the files were renamed after installation. Add the route manually in System → Users → User Groups, or reinstall the module. The mechanics are described in the article about [module access rights](https://opencartcode.com/en/wiki/dev-mvc/opencart-module-access-permissions).
- **White page or class error.** The class name or namespace does not match the path. Check System → Maintenance → Error Logs.
- **The module is enabled, but not on the site.** It was not added to a layout, the status is disabled, or the key was saved without the `module_` prefix.
- **Template changes are not visible.** The Twig cache is at work. In 3.0 it is turned off with the gear button on the Dashboard (developer settings). In 4.1, clearing the cache in the admin and the `storage/cache` folder helps.
- **In 4.1 saving does not work.** Usually the cause is invalid JSON in the response (PHP errors or extra output before the JSON), or the controller path or namespace does not match the route. The `Content-Type: application/json` header should be added, but it is not a typical cause on its own. A `|` separator in the route will not be the cause: 4.1 automatically replaces it with `.`.

> Do not skip the `hasPermission('modify', ...)` check in the save method, even if the module is "only for yourself". Without it, any admin user with a restricted group, such as a content manager, could change the settings with a direct POST request.

> Develop on a local copy with error display enabled in System → Settings → Server. On a live store, errors should not be shown on screen, only written to the log.

## Summary

A first OpenCart module consists of six files: a controller, a language file, and a template for both the admin and the storefront. Plus `install.json` in 4.1. The file path is the route and defines the class name. In 3.0 this is `ControllerExtensionModuleHello` in `extension/module/`. In 4.1 it is the `Hello` class in the `...\Extension\Hello\Module` namespace inside `extension/hello/`. Settings are stored via `model_setting_setting->editSetting()` with the `module_hello` prefix, and it is `module_hello_status` that enables display. The module will work only after installation in Extensions → Extensions with the "Modules" type selected and after being added to a layout.

Next, it is worth looking at how the [Loader loads controllers, models, and templates](https://opencartcode.com/en/wiki/dev-architecture/opencart-loader), adding `install()`/`uninstall()` methods with custom tables, and building a multi-instance version of the module. All these topics are collected in the section [Creating Modules for OpenCart](https://opencartcode.com/en/wiki/dev-extensions).

## FAQ

**Can one archive install a module on both OpenCart 3.0 and 4.1?**

No. The folder structure, class names, and archive format differ, so a separate package is built for each branch. Only the model logic and templates can be shared, and only after adapting the paths.

**How do I make a module that can be added to layouts several times with different settings?**

Use model setting/module instead of model setting/setting. Each instance is stored in the module table with its own module_id, and the storefront passes its settings to the controller's index() method.

**Is it necessary to write an install() method in the admin controller?**

No, for a simple module without its own tables or events it isn't needed. The core will create the extension record and grant permissions itself. install() is needed when you have to create tables or register events.

**Will a module keep working after upgrading OpenCart to a new minor version?**

Usually yes, if you haven't edited core files and only added your own. The risk appears when moving between the 3.0 and 4.1 branches, or between early and later 4.0 releases, where routes and API changed.

**Why do a module's settings disappear after it is deleted?**

When you click “Delete” in the module list, the core removes settings with the code module_hello from the setting table. If the settings must survive reinstallation, keep them in your own table.
