Back to Top

Create your first basic module in Opencart

Updated 16 July 2021

The Opencart is one of the great examples of MVC framework as it provides separate folders for controller, model, view and language. In order to start creating your first Opencart module, you must know the basic fundamentals of Opencart. You can learn the basic fundamentals of Opencart by visiting Opencart documentation. For creating a module in Opencart, you have to follow a directory structure. You can learn about the directory structure here.

So, in order to start module development in Opencart, you have to create a file in module folder of each controller, language and view. You don’t need to create a model file in module development as your values of the module will be stored in a table named setting. The queries for saving the values in setting table is written in admin->model->setting->setting.php file.

We will first learn the module development in Opencart 2.2.0.0. The development details and change in the code according to other versions will be provided in the comments part of the code provided by us.

First, we will create the module’s language file named first_module.php in admin->language->en-gb->module folder. This path will be for the Opencart version 2.2.0.0. For Opencart version 2.3.0.0 and above, we have to create the file in admin->language->en-gb->extension->module. For Opencart version under 2.2.0.0, we have to create the file in admin->language->english->module.

In this file, we will assign the languages to the indexes of an array. Please mind that $_ is the name of the array. Here, is the language, we shall need in the module creation.

Start your headless eCommerce
now.
Find out More
<?php
/**
 * Webkul Software.
 *
 * @category Webkul
 * @package Opencart Module Tutorial
 * @author Webkul
 * @copyright Copyright (c) 2010-2016 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!';

After creating the language, we will head towards the controller. So, we will create a file named first_module.php in admin->controller->module folder. For 2.3.0.0 and upper versions, you have to create the file in admin->controller->extension->module folder.

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) 2010-2016 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)
 * For version 2.3.0.0 and upper, the name of the controller must be ControllerExtensionModuleFirstModule
 */
class ControllerModuleFirstModule 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('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('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', 'token=' . $this->session->data['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', 'token=' . $this->session->data['token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_module'),
			'href' => $this->url->link('extension/module', 'token=' . $this->session->data['token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('module/first_module', 'token=' . $this->session->data['token'], true)
		);
		/**
		 * Form action url is created and defined to $data['action']
		 */
		$data['action'] = $this->url->link('module/first_module', 'token=' . $this->session->data['token'], true);
		/**
		 * Cancel/back button url which will lead you to module list
		 */
		$data['cancel'] = $this->url->link('extension/module', 'token=' . $this->session->data['token'], true);
		/**
		 * checks whether the value exists in the post request
		 */
		if (isset($this->request->post['first_module_status'])) {
			$data['first_module_status'] = $this->request->post['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['first_module_status'] = $this->config->get('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('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', 'module/first_module')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		return !$this->error;
	}
}

With the above code, you would learn many other things about the Opencart as well like how to load language, model etc and how to make their use.

After the controller, we have to go for the view file. So, we will create a file named first_module.tpl in admin->view->template->module folder. For 2.3.0.0 and upper versions, you have to create the file in admin->view->template->extension->module folder.

Here’s the view file code.

<!-- 
/**
 * Webkul Software.
 *
 * @category Webkul
 * @package Opencart Module Tutorial
 * @author Webkul
 * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
 * @license https://store.webkul.com/license.html
 */
 -->
<!-- merging the 'header' and 'column left' part with this template -->
<?php echo $header; ?><?php echo $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="<?php echo $button_save; ?>" class="btn btn-primary"><i class="fa fa-save"></i></button>
        <!-- Back button -->
        <a href="<?php echo $cancel; ?>" data-toggle="tooltip" title="<?php echo $button_cancel; ?>" class="btn btn-default"><i class="fa fa-reply"></i></a></div>
      <!-- Heading is mentioned here -->
      <h1><?php echo $heading_title; ?></h1>
      <!-- Breadcrumbs are listed here -->
      <ul class="breadcrumb">
        <?php foreach ($breadcrumbs as $breadcrumb) { ?>
        <li><a href="<?php echo $breadcrumb['href']; ?>"><?php echo $breadcrumb['text']; ?></a></li>
        <?php } ?>
      </ul>
    </div>
  </div>
  <div class="container-fluid">
    <!-- if it contains a warning then it will be visible as an alert -->
    <?php if ($error_warning) { ?>
    <div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
      <button type="button" class="close" data-dismiss="alert">&times;</button>
    </div>
    <?php } ?>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title"><i class="fa fa-pencil"></i> <?php echo $text_edit; ?></h3>
      </div>
      <div class="panel-body">
        <!-- form starts here -->
        <form action="<?php echo $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"><?php echo $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 "first_module_" after that status is added -->
              <select name="first_module_status" id="input-status" class="form-control">
                <?php if ($first_module_status) { ?>
                <option value="1" selected="selected"><?php echo $text_enabled; ?></option>
                <option value="0"><?php echo $text_disabled; ?></option>
                <?php } else { ?>
                <option value="1"><?php echo $text_enabled; ?></option>
                <option value="0" selected="selected"><?php echo $text_disabled; ?></option>
                <?php } ?>
              </select>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
<!-- merges the footer with the template -->
<?php echo $footer; ?>

So, here we complete with 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.

You can also optimise your code by following this.

Hope, you learn something from this blog. Keep following our blog, to know more about the Opencart.

. . .

Leave a Comment

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


14 comments

  • Natalie
    • Webkul Support
  • repetitor
    • repetitor
      • ahmed
        • Vikhyat Sharma
    • repetitor
      • Webkul Support
        • Kevin
          • Atendra Singh Jadon
          • Kevin
          • Vikhyat Sharma
  • Lesna Vevericka
    • Vikhyat Sharma
  • Back to Top

    Message Sent!

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

    Back to Home