Home Opencart Ecommerce Templates Opencart 4 Events by Examples – Opencart Tutorial

Opencart 4 Events by Examples – Opencart Tutorial

In this Opencart tutorial, we go through OpenCart Events, Opencart events are hooks that developers can attach custom code to, allowing them to execute specific actions at different points in the application’s lifecycle. Events can be triggered by various actions within the OpenCart system, such as user authentication, order creation, product editing, email sending, and more.

Event Types

Pre-Events:

Triggered before a specific action occurs. For example, a pre-event can be triggered before an order is saved, allowing developers to perform custom actions like validating order data.

Post-Events:

Triggered after a specific action occurs. For example, a post-event can be triggered after a product is edited, allowing developers to perform custom actions like updating related data. 

Using OpenCart Events:

To use OpenCart events, developers need to create an event listener, which is a function or method that responds to a specific event. An event completes the tasks that a controller, a model, a theme override, a language, and a config needs to be achieved in the back-end of the store. Upon startup, the Engine automatically registers triggers, and actions, and sorts orders in both the admin/controller/startup/event.php and catalog/controller/startup/event.php files.

Event listeners are registered using the addEvent method from the Event class. The method takes three parameters: the event name, the class/method to be executed, and the priority of the listener.

Example Code:

// In your custom extension, add this code to the controller
$this->event->addEvent('catalog/controller/product/product/after', 'extension/event/custom_event/afterProductView');

// Define the event listener in your custom event class
class ControllerExtensionEventCustomEvent extends Controller {
    public function afterProductView(&$route, &$data, &$output) {
        // Custom code to execute after a product view
        // Example: modify the product data before it's rendered
        $data['custom_text'] = 'This is a custom message after product view.';
    }
}

Registering Events:

Events can be registered in an extension’s install method or directly in the controller if needed.

It’s important to unregister events in the extension’s uninstall method to avoid any unwanted behavior after removing the extension.

Using Events for Customization:

Developers can use OpenCart events to customize and extend the platform in various ways, such as:

Adding custom logic to product pages, checkout processes, or other areas of the platform.

Modifying data before it’s displayed to the user.

Integrating with third-party services or APIs.

For developers, add event code, description, trigger, and action in the database. The action is the method which does what you want. The trigger is the path that you want for the existing Opencart controller and methods.

You can see all the events at >> Admin >> Extensions >> Events

Opencart events list

List of Events

Catalog and admin events, here are the lists of Catalog events for different functionalities.

Language events

OpenCart’s language events system is an important part of managing and customizing language-related aspects of the platform. Language events allow developers to add, modify, or manipulate language files and translations within the OpenCart application. This is crucial for providing multilingual support and customizing text displayed to users.

view/*/beforeDump all the language vars into the template.
controller/*/beforeBefore controller load store all current loaded language data
controller/*/afterAfter controller load restore old language data

Activity events

OpenCart’s activity events system allows developers to monitor and respond to user activities and other important events within the platform. These events are useful for tracking user actions, generating logs, and performing custom operations based on specific activities. This system enhances the ability to understand user behavior, provide better support, and maintain the platform effectively.

Here’s an overview of OpenCart activity events and how you can use them:

Understanding Activity Events:

Activity events in OpenCart track significant actions performed by users, such as login, logout, product views, purchases, and more.

These events enable developers to create custom responses and logs based on specific user activities.

Common Activity Events:

customer_login: Triggered when a customer logs in. This event is useful for monitoring login activity or taking specific actions upon login.

customer_logout: Triggered when a customer logs out. You can use this event to perform cleanup operations or logging.

product_viewed: Triggered when a product is viewed. Useful for tracking product popularity or taking custom actions based on product views.

order_added: Triggered when a new order is added. This event can be used to log order information or trigger post-order processes.

customer_register: Triggered when a customer registers a new account. Useful for sending welcome emails or performing other onboarding activities.

Creating Activity Event Listeners:

To use activity events, create event listeners that respond to specific events of interest.

Register event listeners in your extension’s controller using the addEvent method from the Event class.

// Registering an activity event listener in your controller
$this->event->addEvent('customer_login', 'extension/event/activity/onCustomerLogin');

// Define the event listener method in your custom event class
class ControllerExtensionEventActivity extends Controller {
    public function onCustomerLogin(&$route, &$args, &$output) {
        // Custom code to execute when a customer logs in
        // For example, log the customer login event
        $this->log->write('Customer logged in: ' . $args['customer_id']);
    }
}

Here are default Opencart Activity Event list:

catalog/model/account/customer/addCustomer/after
catalog/model/account/customer/editCustomer/after
catalog/model/account/customer/editPassword/after
catalog/model/account/customer/deleteLoginAttempts/after
catalog/model/account/customer/editCode/after
catalog/model/account/customer/addTransaction/after
catalog/model/account/affiliate/addAffiliate/after
catalog/model/account/affiliate/editAffiliate/after
catalog/model/account/address/addAddress/after
catalog/model/account/address/editAddress/after
catalog/model/account/address/deleteAddress/after
catalog/model/account/returns/addReturn/after
catalog/model/checkout/order/addHistory/before

Statistics events

catalog/model/catalog/review/addReview/after
catalog/model/account/returns/addReturn/after
catalog/model/checkout/order/addHistory/before

Theme event

OpenCart’s theme events system allows developers to customize and extend the behavior of themes within the platform. By using Theme events, you can modify how themes render content, alter page elements, and integrate custom logic to achieve a unique look and feel for your store.

Here’s an overview of OpenCart theme events and how you can utilize them:

Understanding Theme Events:

Theme Events are hooks that allow you to customize the rendering of pages and elements in your OpenCart theme.

These events are triggered during different stages of the rendering process and provide opportunities to manipulate the data or layout before it’s displayed to users.

Common Theme Events:

view/*/before: Triggered before rendering a view file in a specific directory, such as catalog/view/theme/[theme_name].

view/*/after: Triggered after rendering a view file in a specific directory.

template/*/before: Triggered before rendering a template file in a specific directory, such as catalog/view/theme/[theme_name]/template.

template/*/after: Triggered after rendering a template file in a specific directory.

Creating Theme Event Listeners:

To use the theme events, you need to create event listeners that respond to the specific events you want to customize.

Register event listeners in your extension’s controller using the addEvent method from the Event class.

// Registering a theme event listener in your controller
$this->event->addEvent('view/common/header/before', 'extension/event/theme/customizeHeader');

// Define the event listener method in your custom event class
class ControllerExtensionEventThemeCustomizeHeader extends Controller {
    public function customizeHeader(&$route, &$data, &$output) {
        // Custom code to modify the header before rendering
        $data['custom_message'] = 'Welcome to our store!';
    }
}

Here are lists of Opencart theme events:

view/*/before
view/*/after
template/*/before
template/*/after

Here is the main code for the catalog that controls the theme events: upload/catalog/controller/event/theme.php

class Theme extends \Opencart\System\Engine\Controller {
	/**
	 * Index
	 *
	 * @param string            $route
	 * @param array<int, mixed> $args
	 * @param string            $code
	 *
	 * @return void
	 */
	public function index(string &$route, array &$args, string &$code): void {
		// If there is a theme override we should get it
		$this->load->model('design/theme');

		$theme_info = $this->model_design_theme->getTheme($route, $this->config->get('config_theme'));

		if ($theme_info) {
			$code = html_entity_decode($theme_info['code'], ENT_QUOTES, 'UTF-8');
		}
	}
}

Admin Currency Events

model/setting/setting/editSetting
model/localisation/currency/addCurrency
model/localisation/currency/editCurrency

Admin Statistics Events

admin/model/catalog/review/addReview/after
admin/model/catalog/review/deleteReview/after
admin/model/sale/returns/addReturn/after
admin/model/sale/returns/deleteReturn/after

Translation Event

OpenCart’s translation events system allows developers to customize and extend the language and translation aspects of the platform. By using translation events, you can modify or extend the existing translations, add new language strings, and customize language files to achieve a more personalized or localized experience for your store. Here is the main code that you can find at upload/catalog/controller/event/translation.php and upload/admin/controller/design/translation.php

class Translation extends \Opencart\System\Engine\Controller {
	/**
	 * Index
	 *
	 * @param string $route
	 * @param string $prefix
	 *
	 * @return void
	 */
	public function index(string &$route, string &$prefix): void {
		$this->load->model('design/translation');

		$results = $this->model_design_translation->getTranslations($route);

		foreach ($results as $result) {
			if (!$prefix) {
				$this->language->set($result['key'], html_entity_decode($result['value'], ENT_QUOTES, 'UTF-8'));
			} else {
				$this->language->set($prefix . '_' . $result['key'], html_entity_decode($result['value'], ENT_QUOTES, 'UTF-8'));
			}
		}
	}
}

Admin Language Events

view/*/before
controller/*/before
controller/*/after

Testing Output with Opencart Events

By default, in the system/config/catalog.php file, the debug key and value are commented out at the bottom of the file because they should only be active for debugging purposes. Remove the comment of the code like below:

// Action Events
$_['action_event']      = [
	'controller/*/before' => [
		0 => 'event/modification.controller',
		1 => 'event/language.before',
		2 => 'event/debug.before'
	],
	'controller/*/after' => [
		0 => 'event/language.after',
		2 => 'event/debug.after'
	],
	'view/*/before' => [
		0   => 'event/modification.view',
		500 => 'event/theme',
		998 => 'event/language'
	],
	'language/*/before' => [
		0 => 'event/modification.language'
	],
	'language/*/after' => [
		0 => 'startup/language.after',
		1 => 'event/translation'
	]
];

After enabling debugging, you can test the code within the catalog/controller/event/debug.php file. You see the after and before methods. Here is an example of an after-method test to find all the routes used on the page.

Opencart events debugging

It is essential to undo the changes of the debugging by commenting out the debugs line in the system/config/catalog.php file after testing.

Challenges

  • Performance Impact: Every event adds a layer of processing, which can slightly impact page load times, especially with numerous event handlers. Monitor performance and prioritize essential events to avoid noticeable slowdowns.
  • Debugging Complexity: Debugging problems within event handlers can be more challenging than traditional code because they may be triggered from different locations. Employ proper logging and testing practices to identify and resolve issues effectively.
  • Security Risks: Improper event handler implementation might introduce security vulnerabilities. Always validate and sanitize user input within event handlers to prevent potential security risks.
  • Maintenance burden: As your store and codebase grow, managing numerous event handlers can become complex. Organize your events and handlers logically, document their purpose, and update them regularly to maintain code clarity and avoid conflicts.
  • Version compatibility: While events strive for backward compatibility, updates to core files or other extensions might break event handlers. Thoroughly test your events after updates to ensure continued functionality.

Best Practices while using Opencart Events:

  • Use events judiciously: Don’t overuse events for simple tasks that can be handled efficiently within core files. Reserve events for extending functionality beyond core capabilities.
  • Write clean and efficient code: Optimize your event handlers for performance and avoid unnecessary processing.
  • Test thoroughly: Test your event handlers under various scenarios, including edge cases and potential conflicts with other extensions.
  • Document your work: Document the purpose and logic of your event handlers to facilitate future maintenance and collaboration.
  • Stay updated: Monitor changes in OpenCart and event-related functionality to adapt your code when necessary.

2 COMMENTS

  1. I tried opencart 4 events but its not calling function of my class. My file name is soscodes_custom.php and I created it under “extension/soscodes/admin/controller/event/soscodes_custom.php”

    namespace Opencart\Admin\Controller\Extension\Soscodes\Event;

    class SoscodesCustom extends \Opencart\System\Engine\Controller {

    public function product_data_form_after(string &$route, array &$data, mixed &$output): void {
    echo “here” exit;
    }
    }

    Trigger: admin/view/catalog/product_form/after
    Action: extension/soscodes/event/soscodes_custom.product_data_form_after

LEAVE A REPLY

Please enter your comment!
Please enter your name here