Reading list Switch to dark mode

    How to create a module in Opencart version 4?

    Updated 19 December 2023

    Opencart is a popular e-commerce platform enabling users to create online stores and sell products. Developing a custom module in Opencart enhances store functionality and delivers an enhanced user experience for customers.

    In version 4, opencart extensions have been relocated. Previously stored in “admin > controller > extension > module”, they are now found in the “extension” directory within the Opencart root directory.

    The folder currently consists of an Opencart directory and an index.html file as its default contents. When you navigate to this folder, you will see all of the default extensions that are provided by Opencart.

    Folder Structure

    Screenshot-from-2023-12-19-10-36-31

    Module backend code

    Finally, we have our folder structure in place, let’s start creating an extension, we will show a ” Webkul ” menu on the customer account page.

    Searching for an experienced
    Opencart Company ?
    Find out More

    admin/controller/module/example_addon.php

    <?php
    /**
     * Extension name: Show Menu
     * Descrption: Using this extension we will add menu at customer account page.
     * Author: Webkul Software Pvt. Ltd. 
     * 
     */
    namespace Opencart\Admin\Controller\Extension\Webkul\Module;
    
    use \Opencart\System\Helper AS Helper;
    
    class ExampleAddon extends \Opencart\System\Engine\Controller {    
        
       /**
       * index
       *
       * @return void
       */
       public function index(): void {
          $this->load->language('extension/webkul/module/example_addon');
          $this->document->setTitle($this->language->get('heading_title'));
    
          $data['breadcrumbs'] = [];
    
          $data['breadcrumbs'][] = [
             'text' => $this->language->get('text_home'),
             'href' => $this->url->link('common/dashboard','user_token='    .$this->session->data['user_token'])
          ];
    
          $data['breadcrumbs'][] = [
             'text' => $this->language->get('text_extension'),
             'href' => $this->url->link('marketplace/extension','user_token='. $this->session->data['user_token'] . '&type=module')
          ];
    
          if (!isset($this->request->get['module_id'])) {
             $data['breadcrumbs'][] = [
                'text' => $this->language->get('heading_title'),
                'href' => $this->url->link('extension/webkul/module/example_addon','user_token='. $this->session->data['user_token'])
          ];
          } else {
             $data['breadcrumbs'][] = [
                'text' => $this->language->get('heading_title'),
                'href' => $this->url->link('extension/webkul/module/example_addon','user_token='. $this->session->data['user_token'] . '&module_id=' . $this->request->get['module_id'])
          ];
          }
             
          // configuration save URL
          $data['save'] = $this->url->link('extension/webkul/module/example_addon.save', 'user_token=' . $this->session->data['user_token']);
             
          // back to previous page URL
          $data['back'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module');
    
          // getting status from extension configuration
          $data['module_webkul_status'] = $this->config->get('module_webkul_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/webkul/module/example_addon', $data));
       }
          
       /**
       * save method
       *
       * @return void
       */
       public function save(): void {
          $this->load->language('extension/webkul/module/example_addon');
          $json = [];
    
          if (!$this->user->hasPermission('modify', 'extension/webkul/module/example_addon')) {
          $json['error']['warning'] = $this->language->get('error_permission');
          }
    
       if (!$json) {
          $this->load->model('setting/setting');
          
          // saving configuration
          $this->model_setting_setting->editSetting('module_webkul_status', $this->request->post);
    
          $json['success'] = $this->language->get('text_success');
       }
    
       $this->response->addHeader('Content-Type: application/json');
       $this->response->setOutput(json_encode($json));
       }
       
       /**
       * install method
       *
       * @return void
       */
       public function install() {
          // registering events to show menu
          $this->__registerEvents();
       }
    
       /**
       * __registerEvents
       *
       * @return void
       */
       protected function __registerEvents() {
          // events array
         $events   = array();
         $events[] = array(
           'code'        => "webkulShowMenu",
           'trigger'     => "catalog/view/common/header/after",
           'action'      => "extension/webkul/event/event",
           'description' => "Customer Account Menu",
           'status'      => 1,
           'sort_order'  => 0,
        );
            
          // loading event model
        $this->load->model('setting/event');
        foreach($events as $event){
    
               // registering events in DB
                $this->model_setting_event->addEvent($event);
        }
      }
    
    }

    admin/language/en-gb/module/example_addon.php

    <?php
    // Heading
    $_['heading_title']    = 'Webkul Show Menu';
    
    // Text
    $_['text_extension']   = 'Extensions';
    $_['text_success']     = 'Success: You have modified show menu module!';
    $_['text_edit']        = 'Edit Show Menu Module';
    
    // Entry
    $_['entry_status']     = 'Status';
    
    // Error
    $_['error_permission'] = 'Warning: You do not have permission to modify account module!';

    admin/view/template/module/example_addon.twig

    {{ header }}{{ column_left }}
    <div id="content">
       <div class="page-header">
          <div class="container-fluid">
    	 <div class="float-end">
    	    <button type="submit" form="form-module" data-bs-toggle="tooltip" title="{{ button_save }}" class="btn btn-primary">
                   <i class="fa-solid fa-save"></i>
                </button>
    	     
                <a href="{{ back }}" data-bs-toggle="tooltip" title="{{ button_back }}" class="btn btn-light">
                   <i class="fa-solid fa-reply"></i>
                </a>
             </div>
             
             <h1>{{ heading_title }}</h1>
    	    
             <ol class="breadcrumb">
    	    {% for breadcrumb in breadcrumbs %}
    	      <li class="breadcrumb-item">
                     <a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a>               
                  </li>
    	    {% endfor %}
    	 </ol>
          </div>
       </div>
       <div class="container-fluid">
          <div class="card">
    	 <div class="card-header">
                <i class="fa-solid fa-pencil"></i> {{ text_edit }}
             </div>
    
    	 <div class="card-body">
                <form id="form-module" action="{{ save }}" method="post" data-oc-toggle="ajax">
    		<div class="row mb-3">
                       <label for="input-status" class="col-sm-2 col-form-label">
                         {{ entry_status }}
                       </label>
    		   <div class="col-sm-10">
    		      <div class="form-check form-switch form-switch-lg">
    			  <input type="hidden" name="module_webkul_status" value="0"/>
    			   <input type="checkbox" name="module_webkul_status" value="1" id="input-status" class="form-check-input"{% if module_webkul_status %} checked{% endif %}/>
    		      </div>
    		   </div>
    		</div>
    	    </form>
    	 </div>
          </div>
       </div>
    </div>
    {{ footer }}

    Frontend code

    Now, we are creating an event file under “catalog/controller/event/event.php”.

    Previously, we registered the event during the module installation with the “_registerEvents()” method.

    Note: If you are triggering backend side controller/model/view files, then you need to create the backend side of your event file.

    The previous Opencart versions had the ocmod feature to make changes in core files but now in version 4 Opencart removed the ocmod and made the extension event-based.

    catalog/controller/event/event.php

    <?php
    /**
     * Extension name: Show Menu
     * Descrption: Using this extension we will add menu at customer account page.
     * Author: Webkul Software Pvt. Ltd. 
     * 
     */
    namespace Opencart\Catalog\Controller\Extension\Webkul\Event;
    
    class Event extends \Opencart\System\Engine\Controller
    {
        /**
         * index
         * Event trigger: catalog/model/catalog/review/addReview/after
         * @param  mixed $route
         * @param  mixed $data
         * @param  mixed $output
         * @return void
         */
        public function index(&$route = false, &$data = array(), &$output = array()): void {
    
            $template_buffer = $this->getTemplateBuffer($route, $output);        
    
            $layout =   '<li class="list-inline-item">
                            <a href="#javascript">
                                <i class="fa-solid fa-cog"></i>
                            </a> 
                            <span class="d-none d-md-inline">Webkul Settings</span>
                        </li>';
            $find = '<div class="nav float-start">';
            $replace = '<div class="nav float-start">' . $layout;
            $output = str_replace($find, $replace, $template_buffer);
        }
    
        /**
         * getTemplateBuffer
         *
         * @param  mixed $route
         * @param  mixed $event_template_buffer
         * @return string
         */
        protected function getTemplateBuffer($route, $event_template_buffer) {
    
            // if there already is a modified template from view/*/before events use that one
            if ($event_template_buffer) {
                return $event_template_buffer;
            }
        }
    }

    Once you have created the extension, you will need to include some information within the module’s “install.json” file. This file supports the following keys: name, version, author, and link.

    {
      "name": "Example Extension",
      "version": "1.0",
      "author": "Webkul Software Pvt. Ltd.",
      "link": "https://www.webkul.com",
      "instruction": ""
    }

    Once install.json is inside the directory, you can zip it and name it that ends with .ocmod.zip, then upload it from the Opencart extension installer.

    ocv4 addon installation

    After that extension will appear on the “Extensions/Extensions/Module”.

    Extensions-1

    After completing all the steps the menu will show on the frontend end in the header section.

    account page

    These instructions will guide you through the process of creating a module for Opencart.

    If you need custom Opencart Development services then feel free to reach us and also explore our exclusive range of Opencart Addons.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    2 comments

  • JV
    • Yash Gupta (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home