Reading list Switch to dark mode

    How to create a module in Opencart?

    Updated 20 April 2023

    Introduction

    One of the best MVC framework examples is Opencart, which offers distinct folders for the controller, model, view, and language. Remember when building your new module in opencart, it required to be familiar with the platform’s foundational concepts. This will enable you to create modules that align with Opencart’s structure and specifications. Visit the Opencart documentation to discover the foundations of the platform. In Opencart, there is a directory structure that you must adhere to while creating a module in opencart. The directory structure is described here.

    Therefore, you must create a file in the module folder of each controller, language, and view in order to begin module development in Opencart. The values for the module in opencart will be stored in a table called setting, which you don’t require when you are creating a model file when creating a module. The admin->model->setting->setting.php file contains the queries for saving the settings in the setting table.

    General Information

    We will first become familiar with Opencart 3.0.3.8’s module development. The comments section of the code that we give will include development information and changes made in response to changes in other versions.

    Folder Structure

    You need to follow the folder structure given below

    folder_structure-1

    Create A Language File For The First Module

    The language file for the module, ‘first_module.php’, will be created in the beginning and placed in the admin->language->en-gb->extension>module folder. For Opencart version 3.0.3.8, use this path.

    Searching for an experienced
    Opencart Company ?
    Find out More

    The languages in this file will allocate to an array’s indexes. The array’s name is $_, so keep that in mind. The language that will be necessary for creating the module is provided here.

    <?php
    /**
     * Webkul Software.
     *
     * @category Webkul
     * @package Opencart Module Tutorial
     * @author Webkul
     * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
     * @license https://store.webkul.com/license.html
     */
    // Heading
    $_['heading_title']    = 'First Module';
    $_['text_module']      = 'Modules';
    $_['text_success']     = 'Success: You have modified "First Module" module!';
    $_['text_edit']        = 'Edit "First Module" Module';
    // Entry
    $_['entry_status']     = 'Status';
    // Error
    $_['error_permission'] = 'Warning: You do not have permission to modify "First Module" module!';

    Create A Controller File For The First Module

    When the language has been created, we will go-ahead with the controller. So, under the admin->controller->extension->module folder, we will create a file with the name first_module.php for opencart version 3.0.3.8.

    Here, I’m providing the controller code along with the comments.

    <?php
    /**
     * Webkul Software.
     *
     * @category Webkul
     * @package Opencart Module Tutorial
     * @author Webkul
     * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
     * @license https://store.webkul.com/license.html
     */
    /**
     * The controller class must extend the parent class i.e. Controller
     * The controller name must be like Controller + directory path (with first character of each folder in capital) + file name (with first character in capital)
     */
    class ControllerExtensionModuleFirstModule extends Controller {
        /**
         * property named $error is defined to put errors
         * @var array
         */
        private $error = array();
        /**
         * Basic function of the controller. This can be called using route=module/first_module
         */
        public function index() {
            /**
             * Loads the language file. Path of the file along with file name must be given
             */
            $this->load->language('extension/module/first_module');
            /**
             * Sets the title to the html page
             */
            $this->document->setTitle($this->language->get('heading_title'));
            /**
             * Loads the model file. Path of the file to be given
             */
            $this->load->model('setting/setting');
            /**
             * Checks whether the request type is post. If yes, then calls the validate function.
             */
            if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
                /**
                 * The function named 'editSetting' of a model is called in this way
                 * The first argument is the code of the module and the second argument contains all the post values
                 * The code must be same as your file name
                 */
                $this->model_setting_setting->editSetting('module_first_module', $this->request->post);
                /**
                 * The success message is kept in the session
                 */
                $this->session->data['success'] = $this->language->get('text_success');
                /**
                 * The redirection works in this way.
                 * After insertion of data, it will redirect to extension/module file along with the token
                 * The success message will be shown there
                 */
                $this->response->redirect($this->url->link('extension/module', 'user_token=' . $this->session->data['user_token'], true));
            }
            /**
             * Putting the language into the '$data' array
             * This is the way how you get the language from the language file
             */
            $data['heading_title'] = $this->language->get('heading_title');
    
            $data['text_edit'] = $this->language->get('text_edit');
            $data['text_enabled'] = $this->language->get('text_enabled');
            $data['text_disabled'] = $this->language->get('text_disabled');
    
            $data['entry_status'] = $this->language->get('entry_status');
    
            $data['button_save'] = $this->language->get('button_save');
            $data['button_cancel'] = $this->language->get('button_cancel');
            /**
             * If there is any warning in the private property '$error', then it will be put into '$data' array
             */
            if (isset($this->error['warning'])) {
                $data['error_warning'] = $this->error['warning'];
            } else {
                $data['error_warning'] = '';
            }
            /**
             * Breadcrumbs are declared as array
             */
            $data['breadcrumbs'] = array();
            /**
             * Breadcrumbs are defined
             */
            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_home'),
                'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)
            );
    
            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_module'),
                'href' => $this->url->link('extension/module', 'user_token=' . $this->session->data['user_token'], true)
            );
    
            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('heading_title'),
                'href' => $this->url->link('extenison/module/first_module', 'user_token=' . $this->session->data['user_token'], true)
            );
            /**
             * Form action url is created and defined to $data['action']
             */
            $data['action'] = $this->url->link('extension/module/first_module', 'user_token=' . $this->session->data['user_token'], true);
            /**
             * Cancel/back button url which will lead you to module list
             */
            $data['cancel'] = $this->url->link('extension/module', 'user_token=' . $this->session->data['user_token'], true);
            /**
             * checks whether the value exists in the post request
             */
            if (isset($this->request->post['module_first_module_status'])) {
                $data['module_first_module_status'] = $this->request->post['module_first_module_status'];
            } else {
            /**
             * if the value do not exists in the post request then value is taken from the config i.e. setting table
             */
                $data['module_first_module_status'] = $this->config->get('module_first_module_status');
            }
            /**
             * Header data is loaded
             */
            $data['header'] = $this->load->controller('common/header');
            /**
             * Column left part is loaded
             */
            $data['column_left'] = $this->load->controller('common/column_left');
            /**
             * Footer data is loaded
             */
            $data['footer'] = $this->load->controller('common/footer');
            /**
             * Using this function tpl file is called and all the data of controller is passed through '$data' array
             * This is for Opencart 2.2.0.0 version. There will be minor changes as per the version.
             */
            $this->response->setOutput($this->load->view('extension/module/first_module', $data));
        }
        /**
         * validate function validates the values of the post and also the permission
         * @return boolean return true if any of the index of $error contains value
         */
        protected function validate() {
            /**
             * Check whether the current user has the permissions to modify the settings of the module
             * The permissions are set in System->Users->User groups
             */
            if (!$this->user->hasPermission('modify', 'extension/module/first_module')) {
                $this->error['warning'] = $this->language->get('error_permission');
            }
    
            return !$this->error;
        }
    }

    With the above code, you may learn how to load languages, models, and more, as well as how to use them.

    Create A view File For The First Module

    We must go on to the view file after the controller. Therefore, we will create a file called first_module.twig in the admin->view->template->extension->module folder for the opencart version 3.0.3.8.

    Here’s the view file code.

    <!-- 
    /**
     * Webkul Software.
     *
     * @category Webkul
     * @package Opencart Module Tutorial
     * @author Webkul
     * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
     * @license https://store.webkul.com/license.html
     */
     -->
    <!-- merging the 'header' and 'column left' part with this template -->
    {{ header }}{{ column_left }}
    <div id="content">
            <div class="page-header">
                    <div class="container-fluid">
                            <div class="pull-right">
                            <!-- Form submit button -->
                            <button type="submit" form="form-first-module" data-toggle="tooltip" title="{{ button_save }}" class="btn btn-primary"><i class="fa fa-save"></i></button>
                            <!-- Back button -->
                            <a href="{{ cancel }}" data-toggle="tooltip" title="{{ button_cancel }}" class="btn btn-default"><i class="fa fa-reply"></i></a></div>
                            <!-- Heading is mentioned here -->
                            <h1>{{ heading_title }}</h1>
                            <!-- Breadcrumbs are listed here -->
                            <ul class="breadcrumb">
                            {% for breadcrumb in breadcrumbs %}
                                    <li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
                            {% endfor %}
                            </ul>
                    </div>
            </div>
            <div class="container-fluid">
                    <!-- if it contains a warning then it will be visible as an alert -->
                    {% if error_warning %}
                    <div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> {{ error_warning }}
                            <button type="button" class="close" data-dismiss="alert">&times;</button>
                    </div>
                    {% endif %}
                    <div class="panel panel-default">
                            <div class="panel-heading">
                                    <h3 class="panel-title"><i class="fa fa-pencil"></i> {{ text_edit }}</h3>
                            </div>
                            <div class="panel-body">
                            <!-- form starts here -->
                                    <form action="{{ action }}" method="post" enctype="multipart/form-data" id="form-first-module" class="form-horizontal">
                                            <div class="form-group">
                                                    <!-- Entry label is mentioned here -->
                                                    <label class="col-sm-2 control-label" for="input-status">{{ entry_status }}</label>
                                                    <div class="col-sm-10">
                                                    <!-- The name of the form inputs must start with the controller file name followed by a underscore
                                                    like in this case "module_first_module_" after that status is added -->
                                                            <select name="module_first_module_status" id="input-status" class="form-control">
                                                                    {% if module_first_module_status %}
                                                                            <option value="1" selected="selected">{{ text_enabled }}</option>
                                                                            <option value="0">{{ text_disabled }}</option>
                                                                    {% else %} 
                                                                            <option value="1">{{ text_enabled }}</option>
                                                                            <option value="0" selected="selected">{{ text_disabled }}</option>
                                                                    {% endif %}
                                                            </select>
                                                    </div>
                                            </div>
                                    </form>
                            </div>
                    </div>
            </div>
    </div>
    <!-- merges the footer with the template -->
    {{ footer }}

    So, here we complete the module coding part. Now, you have to visit Extensions->Modules, where you can see the “First Module” in the modules listing. From there you can install the module and then configure it

    Steps To Install And Configure The Module

    To see the recent module you are building, you must follow the steps below after adding and creating all the files.

    Step 1: Please allow permission for the module to access and modify the module functionality and feature. By navigating Admin->Setting->User->User_Groups.

    Selection_037
    Selection_038

    Step 2: After providing the necessary permission to the module now you need to go to the module. By navigating Admin->Extension->Extension and clicking on the selection bar to get the module.

    Selection_039

    Step 3: After seeing the module in the module list, you need to install it by clicking the install button of the module.

    Step 4: After successful installation then edit the module by clicking on the edit button and then you will see the module feature and functionality where you can set the requirements as per your intrust.

    Screenshot-from-2023-04-19-12-53-49

    So, here we complete the module installation and configuration part. We hope you learn something from this blog. Keep following our blog, to know more about Opencart.

    You can also optimize your code by following this blog.

    Feel free to get in touch with us if you need custom Opencart development services. Explore our exclusive selection of Opencart Modules as well.

    . . .

    Leave a Comment

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


    Be the first to comment.

    Back to Top

    Message Sent!

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

    Back to Home