Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Getting Started with OpenCart Module Development
Getting Started with OpenCart Module Development

Getting Started with OpenCart Module Development: Master your OpenCart modules and code!

Arrow left icon
Profile Icon Rupak Nepali
Arrow right icon
$40.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.5 (2 Ratings)
Paperback Oct 2013 112 pages 1st Edition
eBook
$21.59 $23.99
Paperback
$40.99
Arrow left icon
Profile Icon Rupak Nepali
Arrow right icon
$40.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.5 (2 Ratings)
Paperback Oct 2013 112 pages 1st Edition
eBook
$21.59 $23.99
Paperback
$40.99
eBook
$21.59 $23.99
Paperback
$40.99

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Getting Started with OpenCart Module Development

Chapter 1. Getting Started with OpenCart Modules

OpenCart is an e-commerce cart application built with its own in-house framework that uses the Model View Controller (MVC) language pattern; thus each module in OpenCart also follows the MVCL patterns. The controller creates logic and gathers data from the model and passes it to display them in the view. The OpenCart modules have admin and catalog folders. The files in the admin folder help in controlling the settings of modules and the files in the catalog folder handle the presentation layer (frontend). Each module has its own files by which it gets modular, and changing one module's file does not affect other modules.

Creating the Hello World module


We assume that you already know PHP and have installed OpenCart, and are familiar with the OpenCart backend and frontend, as well as you have some coding knowledge of PHP.

You are going to create the Hello World module which just has one input box in the admin settings for the module, and the same content is shown on the frontend. The first step to creating a module is using a unique name, so that there will not be a conflict with other modules. The same unique name is used to create the filename and classname to extend the controller and the model.

There are generally six to eight files that need to be created for each module, and they follow a similar structure. If there is an interaction with the database tables, we have to create two extra models. The following screenshot shows the hierarchy of files and folders of an OpenCart module:

So now you know the basic directory structure of OpenCart module. The file structure is divided into two sections admin and catalog. The admin folders and files deal with the setting of the modules and data handling, while the catalog folders and files handle the frontend.

Let's start with an easy way to make a module. You are going to make the duplicate of the default Google Talk module of OpenCart and change it to the Hello World module. We are using Dreamweaver to work with files.

Changes made in the admin folder

Following are the steps to make changes in the admin folder:

  1. Navigate to admin/controller/module/ and copy google_talk.php and paste in the same folder. Rename it to helloworld.php and open it in your favorite text editor, then look for the following line of code:

    classControllerModuleGoogleTalk extends Controller {

    Change the class name to:

    classControllerModuleHelloworld extends Controller {
  2. Now find google_talk and replace all with helloworld as shown in the following screenshot:

  3. Then, save the file.

  4. Navigate to admin/language/english/module/ and copy google_talk.php and paste in the same folder; rename it to helloworld.php and open it. Then look for the following line of code:

    $_['entry_code'] = 'Google Talk Code:<br />
    <span class="help">Goto
      <a href="http://www.google.com/talk/service/badge/New"
        target="_blank">
        <u>Create a Google Talk chatback badge</u>
      </a> and copy &amp; paste the generated code into the 
      text box.
    </span>';
  5. And replace with following code:

    $_['entry_code'] = 'Hello World Content';
  6. Then again find google_talk and replace all with helloworld.

  7. Then, save the file.

  8. Navigate to admin/view/template/module/ and copy the google_talk.tpl file and paste it in the same folder and rename it to helloworld.tpl; open it and look for google_talk and replace it with helloworld and save it.

Changes made in the catalog folder

Following are the steps to make changes in the catalog folder:

  1. Go to catalog/controller/module/ and copy the google_talk.php file and paste it in the same folder and rename it to helloworld.php; open it and look for the following line of code:

    class ControllerModuleGoogleTalk extends Controller {

    Change the class name to :

    class ControllerModuleHelloworld extends Controller {
  2. Now look for google_talk and replace all with helloworld and save it.

  3. Navigate to catalog/language/english/module/ and copy the google_talk.php file and paste it in the same folder and rename it to helloworld.php; open it and look for Live Chat and replace it with Hello World and save it.

  4. Navigate to catalog/view/theme/default/template/module/ and copy the google_talk.tpl file and paste it in the same folder and rename it to helloworld.tpl.

With the preceding file and code changes complete, our Hello World module is ready to be installed. Now log in to the admin section and navigate to Extensions | Modules, then look for Hello World and click on [install], then click on [Edit] of the Hello World module. Then type the content that you would like to show on the frontend in the Hello World Content field. Now click on the Add Module button and adjust the settings as per your requirements and click on Save. With the settings as per the following image, the module will be shown in the User Account links box (Login, My Account, Edit Account, and so on) for the customer to access as per the layout and it will be shown in the right column, as the status is enabled. The following screenshot shows the settings for the Hello World module:

Now navigate to the frontend of the site and click on the My Account link on the home page; you will see the Hello World module as shown in the following screenshot:

Following are the list of files that you need to upload to your live server:

  • admin/language/english/module/helloworld.php

  • admin/controller/module/helloworld.php

  • admin/view/template/module/helloworld.tpl

  • catalog/controller/module/helloworld.php

  • catalog/language/english/module/helloworld.php

  • catalog/view/theme/default/template/module/helloworld.tpl

By uploading the files, installing the module, and providing the settings, your Hello World module is ready to use.

You can change the Hello World text at catalog/language/english/module/helloworld.php to your desired text like Welcome to our Store and type the welcome message at the Hello World Content while setting the module and showing the welcome message at the frontend.

Installing, configuring, and uninstalling a module

There are many default modules in OpenCart. How modules get installed and which are the database tables that hold the settings of the module are really big questions for the developer.

Installing a module

Navigate to admin | Extensions | Modules, where you will find the list of modules. Click on [Install] and the module gets installed, as shown in the following screenshot:

When you click on the [Install] module, the extension/module controller's install function is called. Now open admin/controller/extension/module.php, you will see the public function install(),which performs the permission check. If you get the Permission Denied! message, as shown in the following screenshot, you have to provide the access permission from admin | User | User Group and edit the user and check or tick mark the module/extension, so you will be able to edit the modules.

If you are provided the access, it loads the admin/model/setting/extension.php function install().

public function install($type, $code) {
  $this->db->query("INSERT INTO " . DB_PREFIX ."extension SET `type` = '" . $this->db->escape($type) . "', `code` = '" . $this->db->escape($code) . "'");
}

This means that data is inserted into the extension table of the database with type=module, and code=helloworld, in case of our Hello World module.

Configuring the module

After clicking on [Install] of the module, [Edit] [Uninstall] gets activated; after clicking on [Edit], you will see the configuration section for the module. As per the Hello World module, the following screenshot shows the configuration section on clicking on [Edit]:

The Hello World Content field is saved in the setting table (oc_setting or as per the prefixes used during installation of OpenCart) of the database as per the name of the input box with group column of "helloworld". For this module, navigate to the file admin/view/template/module/helloworld.tpl, where you will find the following code:

<textarea name="helloworld_code" cols="40" rows="5"><?php echo $helloworld_code; ?></textarea>

Thus, the message or text you typed in the text area is passed to the admin/controller/module/helloworld.php controller and the following lines of code is processed:

if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
  $this->model_setting_setting->editSetting('helloworld',$this->request->post);
  $this->session->data['success'] = $this->language->get('text_success');
  $this->redirect($this->url->link('extension/module','token=' . $this->session->data['token'], 'SSL'));
}

It checks if the form is submitted through the POST method and checks whether the Hello World Content field is empty or not with the validate function. If the content is not empty and the form is submitted through the POST method, it calls the editSetting function which is in admin/model/setting/setting.php.

public function editSetting($group, $data, $store_id = 0) {
  $this->db->query("DELETE FROM " . DB_PREFIX . "setting WHERE 
    store_id = '" . (int)$store_id . "' AND `group` = '" . $this-
      >db->escape($group) . "'");
  foreach ($data as $key => $value) {
    if (!is_array($value)) {
      $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET 
        store_id = '" . (int)$store_id . "', `group` = '" . $this-
          >db->escape($group) . "', `key` = '" . $this->db-
            >escape($key) . "', `value` = '" . $this->db-
              >escape($value) . "'");
    } else {
    $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET 
      store_id = '" . (int)$store_id . "', `group` = '" .
        $this->db->escape($group) . "', `key` = '" . $this->
          db->escape($key) . "', `value` = '" . $this->
            db->escape(serialize($value)) . "', serialized = 
              '1'");
    }
  }
}

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com . If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

As given at the controller, $group=helloworld, $data is the $_POST, and $store_id is 0. First it deletes all the Hello World settings and then starts to insert the new values. Following are the rows inserted in the setting table of the database:

If the value of the input field of the form is in array, the value is saved with serialized. Thus serialized becomes 1, or else the value of serialized is 0.

The serialize($value), serialize function of PHP generates a storable representation of a value for an array.

http://php.net/manual/en/function.serialize.php

Layouts for the module

OpenCart has default page layouts that are based on the route of the page. Some of the layouts can be found at admin | System | Design | Layouts, and they are as follows:

  • Account

  • Affiliate

  • Category

  • Checkout

  • Contact

  • Default

  • Home

  • Information

  • Manufacturer

  • Product

  • Sitemap

Now edit one of them, let's consider Account, as shown in the following screenshot:

The value of Route is account; this means that the module will be seen where the route value contains account. If your URL is http://example.com/index.php?route=account/login, the module is shown as route=account. If you want to show the module in the account section, you have to change the layout to Account.

If you like to show the module in affiliate section, you have to choose the Affiliate layout as the route of Affiliate, that is, route=affiliate in the URL.

Similarly, for other layouts, check the route at admin | System | Setting | Design | Layouts | Edit, see the route, and check the URL route; you will find where the module will show on choosing the layout name.

Positions for the module

There are four positions for modules. They are as follows:

  • Column Left

  • Column Right

  • Content Top

  • Content Bottom

The following table shows the available positions for modules in the frontend.

Header

Content Left

Content Top

Content Right

Main Content

Content bottom

Footer

Choose as per your need of module position.

Status of the module

Status shows whether the module is enabled or disabled. If enabled, it is shown at the frontend, else it is not.

Sort order of the modules

If there is more than one module in any of the positions, sort order plays its role. Let us suppose two modules, Hello World and Account, are positioned to the right column of layout Account, and you like to show Hello World first, and then below it, the Account module, you have to insert Sort order 1 for Hello World and Sort order 2 for Account. If you do not insert sort order, it shows at the top. You will then be able to see the modules in the right column, as shown in the following screenshot:

Show same module in different layouts

We can easily show the same module in a different layout. To do this, click on the Add Module button and another row of the table is added; select the appropriate layout, position, status, and the sort order, then click on the Save button. You will be able to see the module in the respective layout. When you click on the Add Module button, the next row is added, as shown in the following screenshot:

Effects of clicking on the Add Module button

The Add Module button shows another row for the module setting. Open admin/catalog/view/template/helloworld.tpl and you will see the following code, which is for the Add Module button:

<a onclick="addModule();" class="button"><?php echo $button_add_module; ?></a>

On clicking the Add Module link, the addModule function is called; the addModule function adds a row just below the previous row.

Uninstalling the module

Navigate to admin | Extensions | Modules, and you will find the list of modules. Just click on [Uninstall], the module gets uninstalled and all settings get deleted. Let's see how it is done. Open admin/controller/extension/module.php, you will see the public function uninstall(),which performs the permission check and if there is permission access, it loads the model setting/extension uninstall function.

File structure – admin and frontend

When someone uses the module, it is reliable to have the admin section so that the user can handle the module functionality as well as position, layout, status, and sort order by which users can show the module wherever they like.

Creating the language files for the admin module in OpenCart

Language files are also named with MODULENAME.php. For example, let's say we want to create a file containing hello world messages or text; we have to create helloworld.php. Language files use "constant=value" configuration. The constant name is used in the code; it never changes, only the value for that language changes. If English language is active, it retrieves the constant from the English language folder's file; if another language is active, it retrieves from the other language folder's file. For example, if English language is active, the constant is taken from the English language folder's file.

$_['text_review'] = 'Product Review';

If Spanish language is active, the constant is taken from the Spanish language folder's file.

$_['text_review'] = 'De Revisión de Producto';

If German language is active, the constant is taken from the German language folder's file.

$_['text_review'] = 'ProduktBewertung';

A similar process is followed for the other languages installed.

Within the file, we will assign each line of text to a variable as $_['variablename']. The same variable name will be used in the controller to access the text or messages. For example, in the following code:

$this->data['heading_title'] = $this->language->get('heading_title');

Now on, we will use the heading_title controller to access the "Hello World" text.

You can see the following code at admin/language/english/module/helloworld.php.

<?php
$_['heading_title']       = 'Hello World';
$_['text_module']         = 'Modules';
$_['text_success']        = 'Success: You have modified module Hello World!';
$_['text_content_top']    = 'Content Top';
$_['text_content_bottom'] = 'Content Bottom';
$_['text_column_left']    = 'Column Left';
$_['text_column_right']   = 'Column Right';
$_['entry_code']          = 'Hello World Content';
$_['entry_layout']        = 'Layout:';
$_['entry_position']      = 'Position:';
$_['entry_status']        = 'Status:';
$_['entry_sort_order']    = 'Sort Order:';
$_['error_permission']    = 'Warning: You do not have permission to modify module Hello World!';
$_['helloworld_content']          = Hello World Content';
?>

Creating the controller in the admin section of the OpenCart module

Controller is the core file where all the logic and magic take place. This is also where the variables for values and language are set and passed to the view variables for display. A Controller in OpenCart is simply a class file that is named in a way that can be associated with a URL.

Consider this URL: http://example.com/index.php?route=module/helloworld.

In the above example, OpenCart would attempt to find a controller file helloworld.php in the module folder with class ControllerModuleHelloworld.

We can see the code at admin/controller/module/helloworld.php whose functionalities are described as follows:

In OpenCart, controller class names must start with the controller and the folder on which the module is located and the filename without extension. For example, in the Hello World module, the class name for the controller is ControllerModuleHelloworld as it is inside the module folder and the filename is helloworld.php. Also, always make sure your controller extends the parent controller class.

class ControllerModuleHelloworld extends Controller {

Whenever the controller is called, the index function (public function index()) is always loaded by default.

$this->language->load('module/helloworld');

The preceding line of code loads the language file variables of helloworld.php which is in the module folder at admin/language/*/module/helloworld.php (* represents the language folder) and now you are able to get the text or messages with reference to variables like $this->language->get('heading_title'). This means the Hello World text is ready to transfer to the template files.

$this->document->setTitle($this->language->get('heading_title'));

The preceding line of code sets the title of the document Hello World.

The $this->load->model('setting/setting') variable loads the setting.php file of the setting folder which is in the model folder. As explained previously, it loads admin/model/setting/setting.php. Your module can load any model file in its controller file using the following code, if they are in the same admin or catalog folder as the controller. You will need to specify the path to the file you want to load from the admin folder within the parentheses. The preceding code will load the settings class so we have access to the functions within the ModelSettingSetting class in our model's controller file. Use the following format in your code to call a function from a loaded model file:

$this->model_setting_setting->editSetting('helloworld',$this->request->post);
if (($this->request->server['REQUEST_METHOD'] == 'POST') &&$this->validate()) {
$this->model_setting_setting->editSetting('helloworld',$this->request->post);$this->session->data['success'] = $this->language->get('text_success');$this->redirect($this->url->link('extension/module','token=' . $this->session->data['token'], 'SSL'));
  }

When a form is saved in the module section, the preceding lines of code, which are at admin/controller/module/helloworld.php run. If the code is submitted through the POST method and validates function return true, all the settings are saved to the database at the setting table and a success message is assigned to the success variable and is redirected to the list of the module page.

protected function validate() {
  if (!$this->user->hasPermission('modify', 'module/helloworld')) {
    $this->error['warning'] = $this->language->get('error_permission');
  }
  if (!$this->request->post['helloworld_code']) {
    $this->error['code'] = $this->language->get('error_code');
  }
  if (!$this->error) {
    return true;
  } else {
    return false;
  }
}

When a form is submitted, validation is checked for whether permission is provided or not. It is checked whether the Hello World Content consists of the text or not. If no access is provided or no content is entered, error is returned true, by which it shows Code Required or Permission Denied! and alerts the user to provide the access or insert the content.

$this->data['heading_title'] = $this->language->get('heading_title');
$this->data['text_enabled'] = $this->language->get('text_enabled');

The $this->language->get('heading_title') variable gets the value of the $_['heading_title'] variable from the language file helloworld.php, which is "Hello World" and is assigned to $this->data['heading_title']. Likewise, for $this->language->get('text_enabled'), "Enabled" is assigned to $this->data['text_enabled'] and the same for the other files.

  if (isset($this->error['warning'])) {
    $this->data['error_warning'] = $this->error['warning'];
  } else {
    $this->data['error_warning'] = '';
  }

The Hello World module checks for access permission and gives a warning if the user has no access to the module.

  if (isset($this->error['code'])) {
    $this->data['error_code'] = $this->error['code'];
  } else {
    $this->data['error_code'] = '';
  }

If no content is inserted in the Hello World Content field and the user tries to save the module, it validates whether the content is inserted or not; if content is not inserted, an error is activated by which it will show the error code as "Code Required".

$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
  'text'      => $this->language->get('text_home'),
  'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
  'separator' => false
);
$this->data['breadcrumbs'][] = array(
  'text'      => $this->language->get('text_module'),
  'href'      => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'),
  'separator' =>' :: '
);
$this->data['breadcrumbs'][] = array(
  'text'      => $this->language->get('heading_title'),
  'href'      => $this->url->link('module/helloworld', 'token=' . $this->session->data['token'], 'SSL'),
  'separator' =>' :: '
);

Breadcrumbs are defined in an array, and contain elements such as text, href, and separator. Text elements hold the word to show in the template file, href holds the link for the word, and separator holds what to use to separate between words. This is shown in the preceding lines of code.

  'text'      => $this->language->get('text_home'),

The preceding line of code holds the "Home" word as per the language file.

  'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),

The preceding line of code holds the link to the "Home" word.

  'separator' => false

The preceding line of code holds the separator between the breadcrumbs; if no separator is needed, false is assigned.

$this->data['action'] = $this->url->link('module/helloworld', 'token=' . $this->session->data['token'], 'SSL');

The preceding line of code will create a link and store it into the action variable. If we have to create the link in the admin area, we have to use it as explained previously. A token is used to preserve the admin user state.

$this->data['modules'] = array();
$this->data['modules'] = $this->config->get('helloworld_module');

An empty array is defined and we assign $this->data['modules'] with all the settings of helloworld_module.

$this->load->model('design/layout');

It loads the layout.php file of the design folder which is in the model folder. As explained previously, it loads admin/model/design/layout.php. The preceding code will load the layout class, so we have access to the functions within the ModelDesignLayout class in our module's controller file.

$this->data['layouts'] = $this->model_design_layout->getLayouts();

The underscores (model_design_layout) refer to the file designations for model/design/layout.php. The layouts variable now holds all the layouts that are created at System | Design | Layout at the admin sections.

$this->template = 'module/helloworld.tpl';
$this->children = array('common/header','common/footer');

In the controller, you will need to load your module's template file in view. To do so, set $this->template to $this->template = 'module/helloworld.tpl', and it loads admin/view/template/module/helloworld.tpl.

$this->response->setOutput($this->render());

The $this->response->setOutput() variable sends data to the browser whether it's HTML or JSON and $this->render constructs the output HTML from the templates/data.

Creating the template file at admin in the OpenCart module

This refers to the template or TPL files. All variables that are passed from the controller to the view can be used for displaying the output of calculations or functionality.

Open the admin/view/template/module/helloworld.tpl file; we are describing the code taking some snippets only.

<?php echo $header; ?>
<?php echo $footer; ?>

The $header and $footer variables are passed from the controller as the template's children.

$this->children = array('common/header','common/footer');

With this, the content of the header and footer are shown on the module section.

Breadcrumbs section for the module

For keeping track of navigation, breadcrumbs are used; in the template file, breadcrumbs are shown by the following lines of code:

<div class="breadcrumb">
<?phpforeach ($breadcrumbs as $breadcrumb) {
  ?>
  <?php echo $breadcrumb['separator']; ?><a href="<?php echo $breadcrumb['href']; ?>"><?php echo $breadcrumb['text'];
  ?></a>
<?php } ?>
</div>

The $breadcrumbs array has been passed by the controller files. The $breadcrumbs array consists of the separator, URL link, and the text to show. All elements of the $breadcrumbs array are managed in the controller.

<?php if ($error_warning) {
  ?>
  <div class="warning"><?php echo $error_warning; ?></div>
<?php } ?>

A warning will show up if you have no permission to access or edit the module. As for the Hello World module, it checks for permission and shows a warning if the user has no access to the module. The following screenshot shows the Breadcrumbs, Header image and Title, and Header save and cancel button:

The following line of code shows the image icon near the heading title:

<h1><imgsrc="view/image/module.png" alt="" /><?php echo $heading_title; ?></h1>

The following line of code shows the heading title that is passed from the controller:

$this->data['heading_title'] = $this->language->get('heading_title');

The following lines of code show the buttons to save and cancel:

<div class="buttons">
  <a onclick="$('#form').submit();" class="button"><?php echo $button_save; ?></a>
  <a href="<?php echo $cancel; ?>" class="button"><?php echo $button_cancel; ?></a>
</div>

On clicking the Save button, the form with ID is submitted; on clicking the Cancel button, it calls the extension/module controller, which means it is redirected to the list of modules.

<form action="<?php echo $action; ?>" method="post"enctype="multipart/form-data" id="form">

When the form code is initiated, it has id=form, which is used in the Save button to submit the form. When we click on the Save button, an action to the module / Hello World controller processes the submitted data.

The <span class="required">*</span> shows the asterisk (*) in red color by the style class required.

<textarea name="helloworld_code" cols="40" rows="5"><?php echo $helloworld_code; ?></textarea>
<?php if ($error_code) {
  ?>
  <span class="error"><?php echo $error_code; ?></span>
<?php } ?>

This is the text area field which holds some data; if this text area is submitted empty, it shows as an error.

<tr>
  <td class="left"><?php echo $entry_layout; ?></td>
  <td class="left"><?php echo $entry_position; ?></td>
  <td class="left"><?php echo $entry_status; ?></td>
  <td class="right"><?php echo $entry_sort_order; ?></td>
  <td></td>
</tr>

The table heading is shown by the preceding code and it will look as shown in the following screenshot:

In the following code snippet, the $module_row variable is defined. It is assigned to zero and is increased with the foreach loop, so it is the count of the module rows that increases on clicking on the Add Module button.

<?php $module_row = 0; ?>
<?phpforeach ($modules as $module) { ?>

The $modules array carries the setting of the module; if it is empty, only the Add Module button is shown.

<select name="helloworld_module[<?php echo $module_row; ?>][layout_id]">
  <?php foreach ($layouts as $layout) {
  ?>
    <?php if ($layout['layout_id'] == $module['layout_id']) {?>
      <option value="<?php echo $layout['layout_id']; ?>"selected="selected"><?php echo $layout['name'];
      ?></option>
    <?php } else { ?>
    <option value="<?php echo $layout['layout_id']; ?>"><?php echo $layout['name']; ?></option>
    <?php } ?>
  <?php } ?>
</select>

The preceding code shows the Layout option. If the layout id matches the module layout id, which has been already saved, the selected layout is shown among other layouts, else layouts are shown as default. The layout arrays have been passed from the controller. Similarly, for the position, select fieldname as helloworld_module with its second element as position.

<select name="helloworld_module[<?php echo $module_row;?>][position]">

As we already know, there are four positions described in OpenCart; they are content top, content bottom, column left, and column right. The position module code for the content top is as follows:

<?php if ($module['position'] == 'content_top') {?>
  <option value="content_top" selected="selected"><?php echo $text_content_top; ?></option>
<?php } else {
  ?>
  <option value="content_top"><?php echo $text_content_top;?></option>
<?php } ?>

If module position is already defined and is equal to content_top, content top is selected, else others are selected as default. It works in a similar way for the content bottom, column left, and column right.

<select name="helloworld_module[<?php echo $module_row;?>][status]">
  <?php if ($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>

The preceding code is to show the module status; if module is enabled, option value is equal to 1, else it is 0. If module status is defined or equal to 1, it shows that the module is already defined, so enabled is selected. If it is not defined, disabled is selected.

<input type="text" name="helloworld_module[<?php echo $module_row;?>][sort_order]" value="<?php echo $module['sort_order']; ?>"size="3" />

The preceding code holds the sort order of the module.

<a onclick="$('#module-row<?php echo $module_row; ?>').remove();"class="button"><?php echo $button_remove; ?></a>

The preceding code line removes the rows when we click on the Remove button.

<a onclick="addModule();" class="button"><?php echo $button_add_module; ?></a>

On clicking on the Add Module link, function addModule is called, which adds a row just below the previous row.

function addModule() {}

The preceding function adds the rows for the modules setting. We can add as many modules as we like, just keep on clicking on the Add Module button. The following screenshot shows multiple rows for setting after clicking on the Add Module button:

Creating the language file for catalog (frontend) module in OpenCart

You can create a language file in a similar way as we did in the admin section. For the frontend, your language file will be located at catalog/language/english/module/MODULENAME.php. The filename should be the same as the module name. As per the Hello World module, the language file name is helloworld.php, it is created at catalog/language/english/module/ and consists only of the following code:

<?php
  // Heading
  $_['heading_title']  = 'Hello World';
?>

The Hello World text is assigned to heading_title; with the same heading_title, it is accessible to the controller.

Creating the controller file for catalog (frontend) module in OpenCart

A controller file of a module for the frontend is found at catalog/controller/module/MODULENAME.php; as per the Hello World module, we can see the helloworld.php files at catalog/controller/module. Since we named the file helloworld.php and put it at module/folder, the controller classname will be ControllerModuleHelloworld.

class ControllerModuleHelloworld extends Controller {

Also, always make sure your controller extends the parent controller class so that it can inherit all its functions.

protected function index() {

The index function is always loaded by default if the second segment of the URL is empty. We can load the module controller at http://example.com/index.php?route=module/helloworld/index or http://example.com/index.php?route=module/helloworld.

Here the second segment of the URI is index; if you have created other functions, we can call the function of the module by passing it into the second segment of the URL.

$this->language->load('module/helloworld');

Loading of language files is done with the preceding line of code. According to the previous line, the helloworld.php file at catalog/language/english/module/ is loaded if English language is active or it will load as per the language activated. For example, if Spanish language is active, it loads from catalog/language/spanish/module/.

$this->data['heading_title'] = $this->language->get('heading_title');

The preceding line fetches the text "Hello World" with $this->language->get('heading_title'); and assigns it to the heading_title variable of the data array. The $heading_title file will show "Hello World" in the template files.

if (isset($this->request->server['HTTPS']) && (($this->request->server['HTTPS'] == 'on') || ($this->request->server['HTTPS']== '1'))) {
    $this->data['code'] = str_replace('http', 'https',html_entity_decode($this->config->get('helloworld_code')));
    } else {
      $this->data['code'] = html_entity_decode($this->config->get('helloworld_code'));
    }

The first line of code checks whether SSL is active. If SSL is active, the link's http of $this->config->get('helloworld_code') is replaced with https.

You will be able to get the value of the setting table in a database by passing the key. For example, consider the setting table of a database that consists of the following rows, as shown in the following screenshot:

If you want to show Dressing Shop, you can get it easily wherever you like in the controller, model, or template files. You just have to type the following line of code:

echo $this->config->get('config_name');

But if serialized is equal to 1, it means that the value is stored in an array.

if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/helloworld.tpl')) {
    $this->template = $this->config->get('config_template') .'/template/module/helloworld.tpl';
    } else {
    $this->template = 'default/template/module/helloworld.tpl';
    }
  $this->render();

You can get an active template name from $this->config->get('config_template'); the preceding lines of code check whether the helloworld.tpl file is on the active template or not. If the file is found in the active template, it uses it, or it will use one from the default template. It will be better if we keep the files on the default theme.

Creating the template file for catalog (frontend) module in OpenCart

You can find the template file at catalog/view/theme/<template name>/module; as for the Hello World module, the file name is helloworld.tpl. OpenCart frontend template files have deeper folder structures than the admin ones because admin sections can have only one template. For the frontend, on the other hand, there can be any number of templates; among them, one is selected from the admin | system | setting | edit | the store and at the store tab choose the best template under the Template field.

A folder named <template name> is created at catalog/view/theme. One of the basic rules in OpenCart is never to edit the default theme template file because if OpenCart does not find certain template files on your theme <template name> folder, it will find them on the default theme. While upgrading, the changes made on your custom theme will also get overridden. If template files are not found on the default theme, it shows the following error:

Notice: Error: Could not load template catalog/view/theme/customtheme/template/module/helloworld.tpl! in system\engine\controller.php

Here, the theme folder's name is customtheme.

If you see this kind of error, it means that helloworld.tpl is missing on the customtheme and default theme folders. So you need to create the helloworld.tpl file at catalog/view/theme/customtheme/template/module/ or catalog/view/theme/default/template/module/. Since the helloworld.tpl file is not the default file of OpenCart, we can place it either on customtheme or in default theme.

If you require any changes on the default theme template files, you have to copy the files and folders to the customtheme folder and make changes on the customtheme folder's files, so upgrading it will help in preserving your changes. The following are the code on catalog/view/theme/default/module/helloworld.tpl.

<div class="box">
  <div class="box-heading"><?php echo $heading_title; ?></div>
  <div class="box-content" style="text-align: center;"><?php echo $code; ?></div>
</div>

The $heading_title file holds the text "Hello World" and $code holds the message or text that is inserted into the Hello World module at the backend.

Summary


In this chapter, we duplicated the Google_talk module to create the Hello World module. Hello World is created, installed, configured, and uninstalled. On configuration, we inserted some data and showed the same at the frontend.

We found out how code works in the Hello World module and its file and folder structure. We also described all the code that we used in the Hello World module's files. Taking reference of Hello World module, we should be able to go through other modules and become familiar with the modules of OpenCart.

Left arrow icon Right arrow icon

Key benefits

  • Learn how to clone OpenCart modules
  • Develop and customize modules, pages, order totals, payments, and shipping extensions in OpenCart
  • Understand the Global Library methods used in OpenCart

Description

OpenCart is an online shopping tool which is free to use. It has become widely popular because of its support for custom extensions and module development. This book helps you understand how to use the features available in OpenCart using step-by-step instructions. Getting Started with OpenCart Module Development gives you step-by-step explanations and illustrations on how to clone, customize, and develop modules and pages with OpenCart. This book shows you how to create custom OpenCart modules and pages which are needed as per the requirements of the clients to manage custom data. It describes each and every code used to make a Hello World module, a feedback module, a tips module, an order total module, and a shipping and payment module. The book covers installing, configuring, and uninstalling modules as well as how to clone them. It also discusses all the available Global Library methods of OpenCart as well as ways to handle the files and folders of a shipping and payment module. At the end of the book, you will learn how to make custom pages to manage data by creating a feedback module and how to create the order total using a tips module. In Getting Started with OpenCart Module Development, you will learn everything you need to know to create custom OpenCart modules.

Who is this book for?

This book is for developers who want to develop OpenCart extensions and for those who want to learn more about the code workflow of OpenCart. Basic knowledge of OpenCart would be an added advantage.

What you will learn

  • Create custom modules using OpenCart
  • Learn how to clone OpenCart modules
  • Understand the Global Library methods used in OpenCart
  • Learn about the featured modules of OpenCart
  • Create order total modules using OpenCart
  • Install, configure, and uninstall modules
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 25, 2013
Length: 112 pages
Edition : 1st
Language : English
ISBN-13 : 9781783280377
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Oct 25, 2013
Length: 112 pages
Edition : 1st
Language : English
ISBN-13 : 9781783280377
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 75.98
OpenCart Theming
$34.99
Getting Started with OpenCart Module Development
$40.99
Total $ 75.98 Stars icon

Table of Contents

3 Chapters
Getting Started with OpenCart Modules Chevron down icon Chevron up icon
Describing The Code of Extensions Chevron down icon Chevron up icon
Creating Custom OpenCart Modules Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.5
(2 Ratings)
5 star 0%
4 star 50%
3 star 0%
2 star 0%
1 star 50%
Vahrokh Vain Jan 23, 2014
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
OpenCart is a very good e-commerce software written in the famous PHP language.It comes with a lot of features, it's free and open source, it's quick to deploy and to customize, it's relatively bug free, much cheaper to install, support and learn than blasoned competitors like Magento.It's the indie and small software house dream come true.OpenCart's major drawback is the scarce, terse and usually obsolete documentation. It's a real pain to create a "module" / extension / plug-in / add-on (yeah these things take many names!), one has to sit down, study a lot of old code and figure out how to implement their changes or their extensions.This book comes in to help the "software practicioneer". I am using this definition because I think it really describes the book in a nutshell.If you want to understand OpenCart in depth, if you want to explore it's inner design model, then you'll probably find little in this book.But if you need the job done, if you have contracted an extension and the clock is ticking, then this book could help you a lot.The big boon is, the book is updated to the latest OpenCart release and this is not a minor detail.It's also written in a simple, practical English, thus international developers (a major portion of OpenCart's developers community) will easily understand the book contents.Moreover, it takes a gradual approach. While it stays quite terse at explaining why a certain OpenCart feature works in a certain way, it shows you the code to implement a certain task. The first task is easy, the subsequent chapters show more and more advanced modules. The author does not spare you any nitty gritty details, so you are presented both with "functional" code and the boilerplate code OpenCart requires to include in its add ons. It goes a bit farter than the title says, it's not just a "Getting Started" but also a "Getting Done".At the end of the book, you will be able to create a quite advanced add on, even if you might not really know why it's been written in that way.Therefore I suggest this book to the seasoned or practitioneer PHP programmer. The former may understand how the whole mechanism works by reading at the provided, relatively simple code, the latter does not even truly want to understand everything, he's focused at getting the job done.To sum it up:Good:- Updated to the latest OpenCart release.- Gets quickly down to the code, without long theory sessions.- The provided code may directly be used almost as-is or extended for your own module.Less good:- It could have detailed a bit more about the design decisions and about how OpenCart works.- The learning curve is short but could be steep for a PHP beginner.
Amazon Verified review Amazon
P. Wright May 10, 2014
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Not very impressed with this - book? 95 pages (3 chapters) of do this do that instructions about cloning and modifying opencart modules. Most developers would get further than this under their own steam. Written in very poor English. Not much to say other than very few potatoes and no meat!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
Modal Close icon
Modal Close icon