# addEvent in OpenCart: registering module events and execution order in 3.0 and 4.1

> How an OpenCart module registers events via addEvent in 3.0 and 4.1, where to put the handler, how to remove events on uninstall, and the order in which the core runs them.

Джерело: https://opencartcode.com/en/wiki/dev-events-ocmod/addevent-opencart
OpenCart: 3.0, 4.1
Оновлено: 2026-11-28

To make an OpenCart module react to core actions, you need to record the event in the `event` table by calling `addEvent` from the `setting/event` model, usually in the `install()` method of the module [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller). In OpenCart 3.0 the method takes five separate parameters, while in 4.1 it takes one array. The execution order in both branches is set by `sort_order` and several non-obvious rules that are worth knowing before the first conflict with another module.

Examples are for OpenCart 4.1. In 4.0.x, model triggers and event handling differ. How triggers are matched and what the handler receives is covered in the article [OpenCart event system: before/after and triggers](https://opencartcode.com/en/wiki/dev-events-ocmod/events-opencart). This article covers the registration practice.

## Where and when should a module register events?

An event is written to the database once, not on every request. The natural place for this is the `install()` method of the module's admin controller. The core calls it when the administrator clicks "Install" in [Extensions](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#extensions) → Extensions with the type set to "Modules".

- **OpenCart 3.0:** `admin/controller/extension/extension/module.php` first grants the current user group the `access` and `modify` permissions, then runs `$this->load->controller('extension/module/' . $extension . '/install')`.
- **OpenCart 4.1:** `admin/controller/extension/module.php` does the same, but the route looks like `'extension/' . $extension . '/module/' . $code . '.install'`, and the response itself is sent as JSON.

Symmetrically, the module's `uninstall()` is called on removal. At that moment the core removes, among other things, the rows from the `extension` and `setting` tables, but **it does not touch the `event` table**: neither in 3.0 nor in 4.1 does the extension removal code call `deleteEventByCode()`. If your `uninstall()` does not delete events, they remain and keep pointing to a controller that may no longer exist.

Extensions → Modules: the «Install» and «Delete» buttons run the module's install() and uninstall() · OpenCart 4.1.0.4

A full installation checklist (tables, settings, permissions) is collected in the article about [install and uninstall of an OpenCart module](https://opencartcode.com/en/wiki/dev-extensions/install-opencart-module), and the module file layout is in the [anatomy of an extension](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-structure).

## How do you call addEvent in OpenCart 3.0?

In 3.0 the model accepts positional parameters. The default status is enabled, and the default priority is 0:

`admin/model/setting/event.php` · OpenCart 3.0.5.1 · lines 3–7

```php
public function addEvent($code, $trigger, $action, $status = 1, $sort_order = 0) {
	$this->db->query("INSERT INTO `" . DB_PREFIX . "event` SET `code` = '" . $this->db->escape($code) . "', `trigger` = '" . $this->db->escape($trigger) . "', `action` = '" . $this->db->escape($action) . "', `sort_order` = '" . (int)$sort_order . "', `status` = '" . (int)$status . "'");

	return $this->db->getLastId();
}
```

A typical pair of methods in `admin/controller/extension/module/my_module.php`:

```php
public function install() {
	$this->load->model('setting/event');

	$this->model_setting_event->deleteEventByCode('my_module');

	$this->model_setting_event->addEvent('my_module', 'catalog/model/checkout/order/addOrderHistory/after', 'extension/module/my_module/orderHistory');
	$this->model_setting_event->addEvent('my_module', 'catalog/view/product/product/before', 'extension/module/my_module/productView', 1, 10);
}

public function uninstall() {
	$this->load->model('setting/event');

	$this->model_setting_event->deleteEventByCode('my_module');
}
```

A few details that affect the result:

- **Trigger** starts with `catalog/` or `admin/`. This determines in which application the event fires. The 3.0 [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) selects only rows with `trigger LIKE 'catalog/%'`, and the admin selects rows with the `admin/` prefix.
- **Action** is a controller route in the same application as the trigger. For a `catalog/…` trigger, the class `Action` looks for a file in `catalog/controller/`: it strips segments from the end of the route until it finds a file, and the stripped segment is treated as the method. So `extension/module/my_module/orderHistory` means the file `catalog/controller/extension/module/my_module.php` and the method `orderHistory()`.
- **Code** is the `varchar(64)` column. Several events of a module can share one code, and `deleteEventByCode()` will delete them all in one query.

## How do you call addEvent in OpenCart 4.1?

In 4.1 the method receives a single associative array and returns `event_id`:

`admin/model/setting/event.php` · OpenCart 4.1.0.4 · lines 35–39

```php
public function addEvent(array $data): int {
	$this->db->query("INSERT INTO `" . DB_PREFIX . "event` SET `code` = '" . $this->db->escape($data['code']) . "', `description` = '" . $this->db->escape($data['description']) . "', `trigger` = '" . $this->db->escape($data['trigger']) . "', `action` = '" . $this->db->escape($data['action']) . "', `status` = '" . (bool)$data['status'] . "', `sort_order` = '" . (int)$data['sort_order'] . "'");

	return $this->db->getLastId();
}
```

There are no default values here: all six keys (`code`, `description`, `trigger`, `action`, `status`, `sort_order`) must be present in the array. If you omit, say, `description`, PHP will emit a warning about the missing key. The error handler in `system/framework.php` will write it to the log, and with error display enabled it will output the text straight into the JSON installation response, so the admin will show a confusing error instead of "Success".

Installing a module from the catalog `extension/my_module/`:

```php
public function install(): void {
	$this->load->model('setting/event');

	$this->model_setting_event->deleteEventByCode('my_module');

	$this->model_setting_event->addEvent([
		'code'        => 'my_module',
		'description' => 'Мій модуль: реакція на зміну статусу замовлення',
		'trigger'     => 'catalog/model/checkout/order.addHistory/after',
		'action'      => 'extension/my_module/module/my_module.orderHistory',
		'status'      => true,
		'sort_order'  => 0
	]);
}

public function uninstall(): void {
	$this->load->model('setting/event');

	$this->model_setting_event->deleteEventByCode('my_module');
}
```

Differences from 3.0 that people most often get wrong:

- The model method in the trigger and the controller method in the action are separated by a **dot**: `order.addHistory`, `my_module.orderHistory`. In 4.1 the class `Action` takes the method after the last dot, and without a dot it calls `index`.
- The order history method is called `addHistory()`, not `addOrderHistory()` as in 3.0.
- Besides `catalog/` and `admin/`, there is the `system/` prefix. A trigger like this is registered in both applications without changes.
- The table gained a `description` column, and `code` was extended to `varchar(128)`.

## How do you write a handler and where should you put it?

A handler is a public method of an ordinary module controller in the application where the trigger fires. For storefront events, this is a controller in the module's catalog part.

| What | OpenCart 3.0 | OpenCart 4.1 |
| --- | --- | --- |
| File | `catalog/controller/extension/module/my_module.php` | `extension/my_module/catalog/controller/module/my_module.php` |
| Class | `ControllerExtensionModuleMyModule extends Controller` | `MyModule extends \Opencart\System\Engine\Controller` in the namespace `Opencart\Catalog\Controller\Extension\MyModule\Module` |
| Signature for `model/…/after` | `orderHistory(&$route, &$args, &$output)` | `orderHistory(string &$route, array &$args, &$output): void` |

In 4.1 the namespace is built from `Factory::controller()`: it takes the route, removes underscores, and capitalizes the letters after `_` and `/`. So the directory `my_module` becomes `MyModule`.

An example for 4.1 that reacts to a change in [order status](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#order-status):

```php
namespace Opencart\Catalog\Controller\Extension\MyModule\Module;
class MyModule extends \Opencart\System\Engine\Controller {
	public function orderHistory(string &$route, array &$args, &$output): void {
		if (!$this->config->get('module_my_module_status')) {
			return;
		}

		$order_id = (int)$args[0];
		$order_status_id = (int)$args[1];

		// ваша логіка: синхронізація з CRM, лист менеджеру тощо
	}
}
```

The arguments of the model method arrive as an `$args` array in the same order as in the signature: for `addHistory()` / `addOrderHistory()` it is `$args[0]`, the order ID, and `$args[1]` is the status ID. The core reads them the same way in its own `event/statistics` handler. The module status check at the beginning is needed because a module disabled in its settings does not disable its events: these are two independent flags.

> In 3.0, do not return anything from a handler unless you want to override the result. Any value other than `null` and `Exception` stops the remaining handlers of the event. In a before event it cancels the call and becomes the result; in an after event it replaces the output.

## In what order do handlers run?

The order is determined by the `Event::register()` method: after each addition it sorts the whole array via `array_multisort($sort_order, SORT_ASC, $this->data)`. This gives rules that are the same for 3.0 and 4.1:

1. **A lower `sort_order` runs earlier.** An event with priority -5 runs before events with 0, and 0 runs before 10.
2. **With equal priority, the order does not match the order of addition.** `array_multisort` then compares the entries themselves: first the trigger strings, then the action objects. We tested this on the `Event` class in both branches: of three handlers with priority 0, the first to run was the one whose trigger was `view/*/before` (the character `*` is smaller than letters), and two with the same trigger `view/product/product/before` followed the alphabetical order of the action routes. If order matters, do not rely on zero; set an explicit `sort_order`.
3. **Core events from the config and module events from the database are in the same array.** The keys of the `action_event` array in `system/config/catalog.php` are their priorities. In 3.0 the storefront has the `view/*/before` handler `event/theme` with priority 500 and `event/language` with 998, so a module event with `sort_order` 10 will run before them.
4. **In 3.0 the chain can be cut short.** `trigger()` returns the first result that is neither `null` nor `Exception`, and it no longer calls the remaining handlers. In 4.1, all of them run.

```mermaid
flowchart TD
A["framework.php: events from action_event"] --> B["startup controllers before startup/event"]
B --> C["startup/event: events from the event table"]
C --> D["register sorts by sort_order"]
D --> E["Loader calls trigger"]
E --> F["handlers from lower sort_order to higher"]
```

This diagram reveals one more limitation: the startup controllers listed in `action_pre_action` are executed by the core directly via `Action::execute()`, without events. Moreover, events from the database are registered only in `startup/event`, so you cannot intercept, for example, `startup/session` or `startup/setting` with a module event. For the startup sequence, see the article on [framework.php and the request path](https://opencartcode.com/en/wiki/dev-architecture/opencart-framework-php).

## How do you update, enable, and disable module events?

The `event` table has no unique key on `code`, only the primary key `event_id`. So calling `addEvent()` again with the same trigger simply creates a second row, and the handler starts firing twice. That is why the line `deleteEventByCode()` at the start of `install()` in the examples above is there: it makes installation repeatable.

To update a module (a new trigger, a changed method name), the same approach is more reliable than point editing: delete all events with the module's code and register the current set. Neither 3.0 nor 4.1 has a separate "edit event" method in the model.

To temporarily disable an event from code:

- **OpenCart 3.0:** `enableEvent($event_id)` and `disableEvent($event_id)` work only by ID. The ID can be obtained from `getEventByCode($code)`, but that method returns **one** row (`LIMIT 1`), so it is not suitable for a module with several events sharing one code.
- **OpenCart 4.1:** there is `editStatus(int $event_id, bool $status)` and the more convenient `editStatusByCode(string $code, bool $status)`, which toggles all events with a code at once.

If a module needs events with different priorities, or they need to be toggled separately, give them different codes with one prefix, for example `my_module_order` and `my_module_product`, and in `uninstall()` remove each one. You can check the state of events manually in Extensions → Events: there you can see the code, trigger, action, status, and priority, and in 4.1 also the description.

In OpenCart 3.0 the standard Events page shows only a long list of rows. That is why duplicates after a reinstall, or events pointing to an already deleted controller, have to be found manually or in the database via [phpMyAdmin](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#phpmyadmin). The free module [OCT Event Manager — event manager for OpenCart 3](https://opencartcode.com/en/marketplace/product/oct-event-manager) shows all events of the store, finds broken and slow handlers, and lets you disable third-party events even when the admin does not open. It works without OCMOD and without core changes.

Extensions → Events: check that the module's trigger and action are recorded without duplicates · OpenCart 4.1.0.4

For debugging, it helps to temporarily write to the log from the handler via `$this->log->write()`: if there is no entry, the trigger did not match or the event is disabled. For more about module settings that are convenient to check in the handler, see the article on [the model setting and the setting table](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-setting).

## Summary

- Register events in `install()` and be sure to delete them in `uninstall()` via `deleteEventByCode()`: the core does not remove them by itself.
- 3.0: `addEvent($code, $trigger, $action, $status = 1, $sort_order = 0)`, the method separator is a slash. 4.1: `addEvent(array $data)` with all six keys, the separator is a dot.
- Start `install()` with `deleteEventByCode()` so that repeated installation does not create duplicates.
- A lower `sort_order` runs earlier; with equal priority, the order is determined by the trigger and action rows, so set the priority explicitly.
- Startup controllers cannot be intercepted by events, and in 3.0 a handler that returns a value stops the rest of the chain.

Next, it makes sense to move on to specific techniques: changing templates via `view/*/before` and intercepting models via `model/*/after`. All articles on this topic are in the section [Events and OCMOD](https://opencartcode.com/en/wiki/dev-events-ocmod).

## FAQ

**Can I register an event manually from the admin panel, without module code?**

No, the "Extensions → Events" page only lets you enable, disable and delete events. A new event is added by code using addEvent or a direct INSERT into the event table.

**Does a user need permissions for the event handler's route?**

No, the handler is called directly by the Action class, and permissions are checked only for the route the user opens. The access and modify permissions are needed for the module's settings page.

**Can one action be assigned to several triggers?**

Yes, just add several rows via addEvent with different triggers and the same action. The handler receives $route, so it can tell which event triggered it.

**Do I need to clear the cache after registering an event?**

No, events are read from the event table on every request in startup/event, so a new event takes effect from the next request.
