OCMOD free module to show product availability on categories pages and modules

This Opencart free Ocmod module will show product availability on categories pages and in the featured module, bestseller module, lastest module and in special module. By default when the product quantity is greater than zero, it will show Availability: In Stock, if the product quantity is zero then it will show the product status assigned while entering the products.

Status is shown when a product is out of stock the one selected below. The default options are: In Stock, Pre-Order, Out Of Stock, and 2-3 Days:

Out of Stock Opencart

Download the module by clicking the below button and go to admin >> Extensions >> Installer >> then upload the downloaded product-availability.ocmod.zip. If you are having an installation problem then watch this video

After that go to admin >> Extensions >> Modifications and clear the cache and you will see the changes in a featured module like the one below:

Featured module Product Availability

Read more: Opencart 4 OCMoD Tutorial

Likewise, you can see the availability in categories pages like below:

Show availability in category page

Please don’t forget to post your questions or comments so that we can add extra topics, free modules, or opencart tutorials that we need to develop which helps to develop quality. You can follow at the Twitter account @rupaknpl and subscribe to the YouTube user opencart tutorial. Thanks a lot.

How to see all variables available in twig template in Opencart?

In Opencart, we can see all the variables that are available in the twig template by just adding the following code in twig page.

<ol>
    {% for key, value in _context  %}
      <li>{{ key }}</li>
    {% endfor %}
</ol>

For e.g., if we want to see all the variables that are on the account login page, then open to catalog/view/theme/default/template/account.twig and paste above code now it will be like below:

Opencart Twig Variables

Now the output will be like below:

Opencart variables twig

Here are the variables available in the account login page.

breadcrumbs
error_warning
action
register
forgotten
redirect
success
email
password
column_left
content_full
content_full_bottom
column_right
content_top
content_bottom
footer
header
code
direction
date_format_short
date_format_long
time_format
datetime_format
decimal_point
thousand_point
text_home
text_yes
text_no
text_none
text_select
text_all_zones
text_pagination
text_loading
text_no_results
button_address_add
button_back
button_continue
button_cart
button_cancel
button_compare
button_wishlist
button_checkout
button_confirm
button_coupon
button_delete
button_download
button_edit
button_filter
button_new_address
button_change_address
button_reviews
button_write
button_login
button_update
button_remove
button_reorder
button_return
button_shopping
button_search
button_shipping
button_submit
button_guest
button_view
button_voucher
button_upload
button_reward
button_quote
button_list
button_grid
button_map
error_exception
error_upload_1
error_upload_2
error_upload_3
error_upload_4
error_upload_6
error_upload_7
error_upload_8
error_upload_999
error_curl
datepicker
backup
heading_title
text_account
text_login
text_new_customer
text_register
text_register_account
text_returning_customer
text_i_am_returning_customer
text_forgotten
entry_email
entry_password
error_login
error_attempts
error_approved
text_logout
text_edit
text_password
text_address
text_wishlist
text_order
text_download
text_reward
text_return
text_transaction
text_newsletter
text_recurring
text_information
text_service
text_extra
text_contact
text_sitemap
text_manufacturer
text_voucher
text_affiliate
text_special
text_powered
text_shopping_cart
text_category
text_checkout
text_search
text_all
text_language
text_currency
text_items
text_empty
text_cart
text_sub_total
text_credit
text_order_id
text_total
_parent

Let us know if you have any questions or suggestions.

Opencart 3 free module to list or display all Reviews of products on one page

This Opencart 3 free module or extension is to list out or display all reviews of products on a page. This is one instance module. It lists out the product name, small description of the product, star rating given to the product and the details of the review and the reviewer name and date with the totals reviews for that product and link to it and products add to cart button, wishlist button, and compare button.

First, download the module by clicking the button below

Go to Admin >> Extensions >> Installer and upload the opencart-reviews-listing.ocmod.zip

Then, go to Admin >> Extensions >> Extensions >> Choose Modules >> Install the All reviews module then edit it. If you need more details on how to install extensions then watch it.

Admin section setting

You will see the admin setting for All reviews module like below:

All reviews show Opencart module

Enter the details.

  • Heading Title at Listing Page
  • Meta Description and Short description
  • Number of Reviews to show in a page
  • Product Image Width
  • Product Image Height
  • Show link in the main menu
  • Status

Frontend

Then in the browser go to https://YOURURL/index.php?route=extension/product/allreviews,

All reviews listing opencart free module

See the demo here: https://webocreation.com/nepalbuddha/index.php?route=extension/product/allreviews

Please don’t forget to post your questions or comments so that we can add extra topics, free module or opencart tutorial that we need to develop which helps to develop ourselves and quality. You can follow at twitter account @rupaknpl and subscribe to YouTube user opencart tutorial. Thanks a lot. Enjoy!

Opencart theme development environment setting up automation: Gulp, package.json, Yarn NPM setup

In this Opencart tutorial, we are setting up the OpenCart theme development environment with a gulp, package.json, yarn or NPM, create files and folder structure for development with the use of SCSS and custom JS and with gulp watch we output them in normal OpenCart theme.

We are already known about AMP(Apache, MySQL, PHP) stack with MAMP, install Opencart 3.0.3.2 and get used to the admin interface and files and folder structure of OpenCart. We are using Microsoft Visual Studio code as an Integrated development environment. Before you start this please have a look at this post where we show you how to make the custom theme in OpenCart with the base theme.

Opencart 3 Theme Gulp, SCSS, ES6 set up

We set up the automation tools for custom themes development, it may not be required for simple development but better to have them for continuous development. Steps for setting up the Opencart theme development environment and its automation can be below:

  1. Download https://github.com/rupaknepali/opencart-theme-developement-gulp-setup/archive/master.zip or clone this repo https://github.com/rupaknepali/opencart-theme-developement-gulp-setup
  2. Go to catalog/view/theme, paste this folder, unzip and rename the folder opencart-theme-development-gulp-setup to your theme name.
  3. Then in terminal go to catalog/view/theme/YOURTHEME/dev and run ‘npm install
  4. After all npm packages installed, open dev/gulpfile.js and change the proxy URL “opencart.loc” to your localhost URL
  5. Then in terminal go to catalog/view/theme/YOURTHEME/dev and run “gulp” and then “gulp watch”
  6. Now make changes in the YOURTHEME/dev/scss files or YOURTHEME/dev/js files or YOURTHEME/dev/image or YOURTHEME/dev/fonts, now you will see the changes.
  7. Now you can start the customization
  8. The following are the files and folders structure.
File and folder structure for theme development

If someone needs more details about the setup then the following steps can help you to set up from the beginning of the Opencart theme development, here we will install node, npm, gulp packages, npm packages as needed and run the gulp to minify CSS and JS and convert the ES6 JS with babel

  1. Download and Install the Node.js

    Go to https://nodejs.org and download the latest version and install it

  2. Install Gulp with npm

    npm install gulp-cli -g

  3. Set up gulpfile.js

    Navigate to your custom theme directory and create dev/ folder then inside it create a JavaScript file named gulpfile.js and paste the following code in it

    https://raw.githubusercontent.com/rupaknepali/opencart-theme-developement-gulp-setup/master/dev/gulpfile.js

  4. Create folders SCSS, Image, JS, Fonts

    These folders hold files where we make changes the changes and the gulp will compile and create files and folders outside of dev/ folder

  5. Set up the package manager

    Type ‘npm init‘ in your terminal from the dev folder as created in step 3. Enter the details that init asked.

  6. Install Dependencies that are needed for gulp.js

    Type ‘npm install –save-dev <packagename> in your terminal, which will download gulp files and its associated dependencies and will create a folder ‘node_modules’. For ours we need:

    npm -i babel/core babel/preset-env babelify browser-sync browserify browserify-shim gulp gulp-autoprefixer gulp-concat gulp-if gulp-notify gulp-options gulp-plumber gulp-rename gulp-sass gulp-sourcemaps gulp-strip-debug gulp-uglify gulp-uglifycss vinyl-buffer vinyl-source-stream

    You can see in package.json following are the dev dependencies:

    “devDependencies”: {
            “@babel/core”: “^7.5.5”,
            “@babel/preset-env”: “^7.5.5”,
            “babelify”: “^10.0.0”,
            “browser-sync”: “^2.26.7”,
            “browserify”: “^16.3.0”,
            “browserify-shim”: “^3.8.14”,
            “gulp”: “^4.0.2”,
            “gulp-autoprefixer”: “^6.1.0”,
            “gulp-concat”: “^2.5.2”,
            “gulp-if”: “^3.0.0”,
            “gulp-notify”: “^3.0.0”,
            “gulp-options”: “^1.1.1”,
            “gulp-plumber”: “^1.2.1”,
            “gulp-rename”: “^1.2.0”,
            “gulp-sass”: “^4.0.2”,
            “gulp-sourcemaps”: “^2.6.5”,
            “gulp-strip-debug”: “^3.0.0”,
            “gulp-uglify”: “^3.0.2”,
            “gulp-uglifycss”: “^1.0.9”,
            “vinyl-buffer”: “^1.0.0”,
            “vinyl-source-stream”: “^2.0.0”
        }

  7. Add some other setting in package.json

    “babel”: {
    “presets”: [
    “@babel/preset-env”
    ]
    },
    “browserify”: {
    “transform”: [
    “browserify-shim”
    ]
    },
    “browser”: {
    “jquery”: “./node_modules/jquery/dist/jquery.js”
    },
    “browserify-shim”: {
    “jquery”: “$”
    },
    “browserslist”: [
    “last 2 version”,
    “> 2%”
    ],

  8. Our full package.json looks like:

    {
        “name”: “opencart-gulp-4-es6”,
        “version”: “1.1.0”,
        “description”: “Opencart theme development with Gulp 4 file setup for Javascript ES6 compiling, plus SCSS, images, and fonts”,
        “author”: “Rupak Nepali <webocreation.com@gmail.com> (https://webocreation.com)”,
        “repository”: {
            “type”: “git”,
            “url”: “https://github.com/rupaknepali/opencart-theme-developement-gulp-setup”
        },
        “keywords”: [
            “opencart”,
            “gulp”,
            “es6”,
            “scss”
        ],
        “devDependencies”: {
            “@babel/core”: “^7.5.5”,
            “@babel/preset-env”: “^7.5.5”,
            “babelify”: “^10.0.0”,
            “browser-sync”: “^2.26.7”,
            “browserify”: “^16.3.0”,
            “browserify-shim”: “^3.8.14”,
            “gulp”: “^4.0.2”,
            “gulp-autoprefixer”: “^6.1.0”,
            “gulp-concat”: “^2.5.2”,
            “gulp-if”: “^3.0.0”,
            “gulp-notify”: “^3.0.0”,
            “gulp-options”: “^1.1.1”,
            “gulp-plumber”: “^1.2.1”,
            “gulp-rename”: “^1.2.0”,
            “gulp-sass”: “^4.0.2”,
            “gulp-sourcemaps”: “^2.6.5”,
            “gulp-strip-debug”: “^3.0.0”,
            “gulp-uglify”: “^3.0.2”,
            “gulp-uglifycss”: “^1.0.9”,
            “vinyl-buffer”: “^1.0.0”,
            “vinyl-source-stream”: “^2.0.0”
        },
        “babel”: {
            “presets”: [
                “@babel/preset-env”
            ]
        },
        “browserify”: {
            “transform”: [
                “browserify-shim”
            ]
        },
        “browser”: {
            “jquery”: “./node_modules/jquery/dist/jquery.js”
        },
        “browserify-shim”: {
            “jquery”: “$”
        },
        “browserslist”: [
            “last 2 version”,
            “> 2%”
        ],
        “license”: “GPL-3.0”,
        “dependencies”: {
            “gulp-clean-css”: “^4.2.0”,
            “gulp-concat-css”: “^3.1.0”
        }
    }

  9. Running automation tool from cmd/terminal.

    Now type ‘gulp ‘ and then ‘gulp watch’

    Opencart Gulp

  10. You will see the browser opened at localhost:3000

    Make the changes in SCSS files, JS files, twig files, add images and fonts and the browser reload will happen and you will see the changes.

How to clone the default theme of Opencart 3 to custom theme?

In this Opencart tutorial, we will show how to create a custom Opencart 3 theme. We will go through the default theme files and folders and then clone default theme to custom theme, install the custom theme, activate it and change the CSS of the custom theme.

First, let’s go through the default core theme files and folders of OpenCart:

In the admin section following are the theme files:

  • admin/controller/extension/theme/default.php
  • admin/language/en-gb/extension/theme/default.php
  • admin/view/template/theme/default.twig

In the catalog section, all the files and folders inside the catalog/view/theme/default are of the default theme.

Now, let’s clone the default theme to a custom theme, for that let’s do the following:

Opencart custom theme files and folders

We are going to create a “webocreation” theme, you can name is anything. Let’s start cloning the files:

  • Go to admin/controller/extension/theme/ and copy default.php and paste it and rename it to webocreation.php, then open it in your editor.
  • Now find the default word and replace it with webocreation.
  • Next, go to admin/language/en-gb/extension/theme/ and copy default.php and paste it and rename it to webocreation.php, then open it in your editor.
  • Do the same, find the default word, and replace it with webocreation.
  • Next, go to admin/view/template/extension/theme/ and copy default.twig and paste it and rename it to webocreation.php, then open it in your editor.
  • Do the same, find the default word, and replace it with webocreation.
  • Now go to catalog/view/theme and copy the whole default folder and paste it and rename the folder to webocreation.
  • Go to catalog/view/theme/webocreation/image and copy default.png and paste it and rename it to webocreation.png
  • Finally go to catalog/view/theme/webocreation/template/common/ and open header.twig and then find default and replace it with webocreation.
  • With this, our webocreation opencart theme is created.

Now let’s activate the webocreation Opencart theme.

  • Log in to the Admin section and in the left menu, navigate to Extensions >> Extensions >> Then choose the Themes in extension type.
  • You will see the themes list, where we will see our Webocreation Store Theme also
  • Click the Install button
  • Then edit it
  • In the Theme Directory choose the “webocreation”
  • Choose Status to Enabled
  • Then enter the details as per your requirement, enter the width and height of images, then click save.
  • Now navigate to System >> Settings >> Edit your store >> and in General tab >> Theme >> select the “Webocreation Store Theme”
  • Your webocreation theme is activated.
Opencart theme settings

Let’s see a demo if really webocreation theme is active

  • Go to catalog/view/theme/webocreation/stylesheet/ and open stylesheet.css and change the color of heading, find the following code:
h1, h2, h3, h4, h5, h6 {
	color: #444;
}

Replace the above code with the following:

h1, h2, h3, h4, h5, h6 {
	color: #64ccc9;
}

If everything is ok then you will see changes in the heading titles, now you can perform any changes you like in the CSS and make it different than the default OpenCart theme.

Let us know if you have any questions or suggestions. In the next post, we will set up a local development environment and setup gulp, package.json, yarn, or NPM and be ready to use the SCSS, minification, and optimization for rapid theme development.

How to install OpenCart on a CentOS VPS

This Opencart tutorial is to show you how to install OpenCart on a CentOS-7 64bit which is an Enterprise-class Linux Distribution VPS (Virtual Private Servers), we install Apache, PHP, MySQL, other PHP packages as needed by Opencart and setup virtual host

Login to your VPS

ssh root@IPPROVIDED

Then enter the password.

Now update your system before installing the applications, by updating your server using the command below

sudo yum update

Now install the apache web server by running the command, if it is already installed then you can skip this step as mostly there are installed

sudo yum install httpd

Now start the apache service, which you can do it by the following command as per your system

sudo service httpd start

Till now you can check by typing the IP address provided, you will see the Apache page, mine IP http://178.33.153.139/ and it shows like below:

Better to activate Apache to start after system boot which we can do by the following command:

chkconfig httpd on

Next, install the MySQL server using the following command:

sudo yum install mysql-server

Tell it which run levels to start on:

sudo /sbin/chkconfig --levels 235 mysqld on

Then start the MYSQL server

sudo service mysqld start

To improve the security of your MySQL server, it is recommended to run the interactive security script. You can do that by using the following command:

sudo mysql_secure_installation

Then it asks multiple questions to set the username and password for the database. Once you remove the anonymous users, then disallowing root login remotely, removing test database and reloading privileges on test database then your MySQL installation should be secure.

Like we did for Apache let’s run the MySQL on reboot by the following command:

chkconfig mysqld on

Now let’s install PHP and the other requirements that are needed for the OpenCart, you need to run the command:

sudo yum install php libapache2-mod-php php-mcrypt php-mysql curl php-curl php-gd php-zip

Once all those PHP packages are installed, our server is almost ready. Next, let’s download and configure OpenCart on your VPS by using the commands below:

sudo mkdir /var/www/html/opencart
cd /var/www/html/opencart
sudo wget https://github.com/opencart/opencart/archive/master.zip
sudo unzip master.zip
sudo mv opencart-master/upload/* .
sudo mv opencart-master/upload/.htaccess.txt .htaccess
sudo rm -f master.zip
sudo cp config-dist.php config.php
sudo cp admin/config-dist.php admin/config.php
sudo chown -R www-data: /var/www/html/opencart
sudo chmod 0755 system/storage/cache/
sudo chmod 0755 system/storage/logs/
sudo chmod 0755 system/storage/download/
sudo chmod 0755 system/storage/upload/
sudo chmod 0755 system/storage/modification/
sudo chmod 0755 image/
sudo chmod 0755 image/cache/
sudo chmod 0755 image/catalog/
sudo chmod 0755 config.php
sudo chmod 0755 admin/config.php

Let’s add Nano Text Editor

yum install nano

Next, create an Apache virtual host for OpenCart

sudo nano /etc/httpd/conf/httpd.conf

Add the following VirtualHost content:

<VirtualHost *:80>
    ServerAdmin admin@domain.com
    DocumentRoot /var/www/html/opencart
    ServerName domain.com
    ServerAlias www.domain.com 
    <Directory /var/www/html/opencart/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory> 
    ErrorLog /var/log/httpd/domain.com-error_log
    CustomLog /var/log/httpd/domain.com-access_log common
</VirtualHost>

Replace domain.com with your actual domain name.

Enable the OpenCart virtual host and restart the Apache webserver using the following commands:

sudo a2ensite opencart
sudo service httpd restart

Login to the MySQL database

mysql -u root -p

Create a MySQL database, user and set up a password for OpenCart:

CREATE DATABASE webocreation;
GRANT ALL PRIVILEGES ON webocreation.* TO 'webocreationuser'@'localhost' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;

Replace webocreation with your database name, webocreationuser with your username and password with your password.

Open a web browser and enter your domain name and start the installation.

Let us know any questions about the VPS Virtual Private Servers and any questions about OpenCart in the comment below.

Opencart 3 custom module development tutorial – Hello World module

In this Opencart 3 tutorial we are showing how to create Opencart 3 custom modules or extensions, this tutorial is for the developer and to add the custom functionalities in the Opencart. Check our hello world workflow.

Modules listing in Opencart admin
  • Before you start, watch the following videos tutorial
  • Then start to work in the admin folder for module management
    For Opencart 2 follow this post: How to create the controller for the Opencart custom module?
    For Opencart 3, it is similar to Opencart 2 with some changes in the view section, which we are showing below.
    • To create the Controller in OpenCart 3, we need to understand at least four methods (index, install, validate and uninstall)
    • To create the language file in OpenCart 3, we need to understand how to create variable and how we can load it in the controller and how it automatically get variable access to view.
    • To create the view in Opencart 3, we need to know twig templating.
  • Then start to work in the catalog for module show in front or presentation
    • It also needed three files language, controller and view
  • Before starting, things to consider while creating the modules are as per Daniel are:
    • You are not allowed to modify any core DB tables. If you need to store any data for your extension you need to create a new table and use joins. But you can insert it into the setting table as the configuration are added to it
    • You are not allowed to overwrite any files.
    • All files are only allowed to be written in extension folders, except templates which of course go under the template folder.
    • All extension should have an admin page that allows configuration
    • Extensions are now prefixed by their category. so paypal_status would become payment_paypal_status
  • Here is the files and folders structure of Hello World module
Hello world opencart

OpenCart identifies existing modules automatically, simply by reading the admin/controller/extension/module folder. Any modules existing in this folder will automatically be shown on the Modules listing page, and on the User Permissions page.

More detail for Opencart 2 are at https://webocreation.com/admin-controller-file-make-hello-world-module-opencart-module-development/

Let’s start with Admin Controller

The file to create is helloworld.php and it should be inside admin/controller/extensions/module/ and start with the following boilerplate code:

<?php
class ControllerExtensionModuleHelloworld extends Controller
{
	private $error = array();
	public function index()
	{ }
	protected function validate()
	{ }
	public function install()
	{ }
	public function uninstall()
	{ }
}

In OpenCart, Every class name of the module should start with ControllerExtensionModule, here in the hello world module, our folder structure is controller >> extension >> module >> helloworld.php so the class name is ControllerExtensionModuleHelloworld then extends the class with the base class controller. Better to have all the four methods index() will run when the controller is loaded or someone clicks the edit button, validate() checks for the admin access and other data validation, install() method runs when we click the install button on the module list page, and uninstall() method runs when we click the uninstall button.

private $error = array();
$error is just a private array which will hold the values if some error occurs, we assign error if users don’t have access, or submitted data are not valid.

Installation method:

This method is called when someone clicks the install + button

public function install()
{
	$this->load->model('setting/setting');
	$this->model_setting_setting->editSetting('module_helloworld', ['module_helloworld_status' => 1]);
}

Here we load the setting model, you can see the editSetting() method at controller >> model >> setting >> setting.php. When the install button is clicked then it deletes all the settings it had with the same code and installs the all values again. While passing the values don’t forget to include the extension in front of the name. Like here our extension is module and name is HelloWorld so it becomes module_helloworld and the same for the variables you are going to save, we are saving the status so module_helloworld_status which need to pass as an array. Let see the setting database table, and you will see how values are stored.

Opencart setting database table

The convention is to add module_ or payment_ or shipping_ or report_ or dashboard_ etc as per your extensions type so it is supported in the cloud base as well.

After installation, we click the edit blue button, which calls the index method whose full code is below which we will describe afterward:

public function index()
{
	$this->load->language('extension/module/helloworld');
	$this->document->setTitle($this->language->get('heading_title'));
	$this->load->model('setting/module');
	if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
		if (!isset($this->request->get['module_id'])) {
			$this->model_setting_module->addModule('helloworld', $this->request->post);
		} else {
			$this->model_setting_module->editModule($this->request->get['module_id'], $this->request->post);
		}
		$this->session->data['success'] = $this->language->get('text_success');
		$this->response->redirect($this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true));
	}
	if (isset($this->error['warning'])) {
		$data['error_warning'] = $this->error['warning'];
	} else {
		$data['error_warning'] = '';
	}
	if (isset($this->error['name'])) {
		$data['error_name'] = $this->error['name'];
	} else {
		$data['error_name'] = '';
	}
	$data['breadcrumbs'] = array();
	$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_extension'),
		'href' => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true)
	);
	if (!isset($this->request->get['module_id'])) {
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('extension/module/helloworld', 'user_token=' . $this->session->data['user_token'], true)
		);
	} else {
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('extension/module/helloworld', 'user_token=' . $this->session->data['user_token'] . '&module_id=' . $this->request->get['module_id'], true)
		);
	}
	if (!isset($this->request->get['module_id'])) {
		$data['action'] = $this->url->link('extension/module/helloworld', 'user_token=' . $this->session->data['user_token'], true);
	} else {
		$data['action'] = $this->url->link('extension/module/helloworld', 'user_token=' . $this->session->data['user_token'] . '&module_id=' . $this->request->get['module_id'], true);
	}
	$data['cancel'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true);
	if (isset($this->request->get['module_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
		$module_info = $this->model_setting_module->getModule($this->request->get['module_id']);
	}
	if (isset($this->request->post['name'])) {
		$data['name'] = $this->request->post['name'];
	} elseif (!empty($module_info)) {
		$data['name'] = $module_info['name'];
	} else {
		$data['name'] = '';
	}
	$this->load->model('localisation/language');
	$data['languages'] = $this->model_localisation_language->getLanguages();
	if (isset($this->request->post['status'])) {
		$data['status'] = $this->request->post['status'];
	} elseif (!empty($module_info)) {
		$data['status'] = $module_info['status'];
	} else {
		$data['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/module/helloworld', $data));
}

Let start understand in detail:

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

This is to load the language file admin >> language >> en-gb (or active language) >> extension >> module >> helloworld.php. Let’s create the language file and add some variables needed:

<?php
// Heading
$_['heading_title']     = 'Hello World Content';
// Text
$_['text_extension']    = 'Extensions';
$_['text_success']      = 'Success: You have modified Hello World Content module!';
$_['text_edit']         = 'Edit Hello World Content Module';
// Entry
$_['entry_name']        = 'Module Name';
$_['entry_title']       = 'Heading Title';
$_['entry_status']      = 'Status';
// Error
$_['error_permission']  = 'Warning: You do not have permission to modify Hello World Content module!';
$_['error_name']        = 'Module Name must be between 3 and 64 characters!';

Now to get access to heading_title in the controller we do like below:

$this->language->get('heading_title')

To assign that heading_title as Title of the page we pass the $this->document->setTitle, click to know all of the objects’ methods of opencart

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

Below is the code of how we define the breadcrumbs array and assign in the data variable and pass it to view.

$data['breadcrumbs'] = array();
$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_extension'),
	'href' => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true)
);
if (!isset($this->request->get['module_id'])) {
	$data['breadcrumbs'][] = array(
		'text' => $this->language->get('heading_title'),
		'href' => $this->url->link('extension/module/helloworld', 'user_token=' . $this->session->data['user_token'], true)
	);
} else {
	$data['breadcrumbs'][] = array(
		'text' => $this->language->get('heading_title'),
		'href' => $this->url->link('extension/module/helloworld', 'user_token=' . $this->session->data['user_token'] . '&module_id=' . $this->request->get['module_id'], true)
	);
}

In the code above we use $this->language->get(‘text_home’) so you may got confused how we got text_home variable although we don’t define in admin >> language >> en-gb >> extension >> module >> helloworld.php, so the trick is we can get access to all variables of admin >> language >> en-gb >> en-gb.php we don’t need to load like other language file. So the breadcrumb here is to create the breadcrumbs array then assign the Home and dashboard URL, then added another link Extension and URL to module page. Then we check if the module is an edited or a new module and show the title and link of respective modules.

Now let’s move to another part of the code, the below part of the code is to create the action URL when someone submits or save the form. Here it checks if it is an active module or not and if it is an active module then it passes module_id in the URL

if (!isset($this->request->get['module_id'])) {
	$data['action'] = $this->url->link('extension/module/helloworld', 'user_token=' . $this->session->data['user_token'], true);
} else {
	$data['action'] = $this->url->link('extension/module/helloworld', 'user_token=' . $this->session->data['user_token'] . '&module_id=' . $this->request->get['module_id'], true);
}

In OpenCart module setting mostly, they have to save button and cancel button so below is the link when someone is redirected when they click the cancel button.

$data['cancel'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true);

The below code is to check if the module exists and if then get the available module information of that module.

if (isset($this->request->get['module_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
	$module_info = $this->model_setting_module->getModule($this->request->get['module_id']);
}

The below code is to set the data of the fields to pass to the view. Here we check if the module name is set or module description and the status like below if nothing is set then we assign the empty.

if (isset($this->request->post['name'])) {
	$data['name'] = $this->request->post['name'];
} elseif (!empty($module_info)) {
	$data['name'] = $module_info['name'];
} else {
	$data['name'] = '';
}

if (isset($this->request->post['module_description'])) {
	$data['module_description'] = $this->request->post['module_description'];
} elseif (!empty($module_info)) {
	$data['module_description'] = $module_info['module_description'];
} else {
	$data['module_description'] = array();
}

if (isset($this->request->post['status'])) {
	$data['status'] = $this->request->post['status'];
} elseif (!empty($module_info)) {
	$data['status'] = $module_info['status'];
} else {
	$data['status'] = '';
}

This below code is to pass the languages to the view, as OpenCart supports multi-language so we are showing you how module_description and status can be set as per the language.

$this->load->model('localisation/language');
$data['languages'] = $this->model_localisation_language->getLanguages();

The below are the data to pass the header, column left and the footer to the view.

$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');

The below code is to set the response output to view.

$this->response->setOutput($this->load->view('extension/module/helloworld', $data));

When someone saves the module then following code run and save the module data in an oc_module table in the JSON format.

$this->load->model('setting/module');
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
	if (!isset($this->request->get['module_id'])) {
		$this->model_setting_module->addModule('helloworld', $this->request->post);
	} else {
		$this->model_setting_module->editModule($this->request->get['module_id'], $this->request->post);
	}
	$this->session->data['success'] = $this->language->get('text_success');
	$this->response->redirect($this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true));
}
module database defined of Opencart

When someone submits the form it validates the data with the validate() method as we call it in index() method like $this->validate(), in validate method we mostly check for the permission and define any other validation needed.

protected function validate()
{
	if (!$this->user->hasPermission('modify', 'extension/module/helloworld')) {
		$this->error['warning'] = $this->language->get('error_permission');
	}

	if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 64)) {
		$this->error['name'] = $this->language->get('error_name');
	}

	return !$this->error;
}

Now the last part of the controller is the uninstall method, it uninstalls and removes all the data when someone clicks the uninstall red button.

public function uninstall()
{
	$this->load->model('setting/setting');
	$this->model_setting_setting->deleteSetting('module_helloworld');
}

Now our last part of admin View or presentation part, as opencart started to use the twig templating so here is the full code of the view part:

{{ header }}{{ column_left }}
<div id="content">
  <div class="page-header">
    <div class="container-fluid">
      <div class="pull-right">
        <button type="submit" form="form-module" data-toggle="tooltip" title="{{ button_save }}" class="btn btn-primary"><i class="fa fa-save"></i></button>
        <a href="{{ cancel }}" data-toggle="tooltip" title="{{ button_cancel }}" class="btn btn-default"><i class="fa fa-reply"></i></a></div>
      <h1>{{ heading_title }}</h1>
      <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 error_warning %}
    <div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> {{ error_warning }}
      <button type="button" class="close" data-dismiss="alert">×</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 action="{{ action }}" method="post" enctype="multipart/form-data" id="form-module" class="form-horizontal">
          <div class="form-group">
            <label class="col-sm-2 control-label" for="input-name">{{ entry_name }}</label>
            <div class="col-sm-10">
              <input type="text" name="name" value="{{ name }}" placeholder="{{ entry_name }}" id="input-name" class="form-control" />
              {% if error_name %}
              <div class="text-danger">{{ error_name }}</div>
              {% endif %}
            </div>
          </div>
          <div class="tab-pane">
            <ul class="nav nav-tabs" id="language">
              {% for language in languages %}
              <li><a href="#language{{ language.language_id }}" data-toggle="tab"><img src="language/{{ language.code }}/{{ language.code }}.png" title="{{ language.name }}" /> {{ language.name }}</a></li>
              {% endfor %}
            </ul>
            <div class="tab-content">
              {% for language in languages %}
              <div class="tab-pane" id="language{{ language.language_id }}">
                <div class="form-group">
                  <label class="col-sm-2 control-label" for="input-title{{ language.language_id }}">{{ entry_title }}</label>
                  <div class="col-sm-10">
                    <input type="text" name="module_description[{{ language.language_id }}][title]" placeholder="{{ entry_title }}" id="input-heading{{ language.language_id }}" value="{{ module_description[language.language_id] ? module_description[language.language_id].title }}" class="form-control" />
                  </div>
                </div>
              </div>
              {% endfor %}
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-2 control-label" for="input-status">{{ entry_status }}</label>
            <div class="col-sm-10">
              <select name="status" id="input-status" class="form-control">
                {% if 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>
  
  <script type="text/javascript"><!--
$('#language a:first').tab('show');
//--></script></div>
{{ footer }}

Here is the output of the view:

Hello world content settings of Opencart

The variable we passed from the controller can be accessible in template file which we can show easily with {{variable_name}}, so we can show header, column left and footer like below:

{{ header }}{{ column_left }}{{ footer }}

All other codes are simple in the view part only thing little complicate is the language for loop section and how we add form field name which will be saved in the database. Here heading title and status are language-specific.

Now the front end part so let’s start to create a file in catalog/ folder, go to catalog >> controller >> extension >> module and create helloworld.php and paste the following code:

<?php
class ControllerExtensionModuleHelloworld extends Controller
{
	public function index($setting)
	{
		if (isset($setting['name'][$this->config->get('config_language_id')])) {
			$data['html'] = html_entity_decode($setting['module_description'][$this->config->get('config_language_id')]['title'], ENT_QUOTES, 'UTF-8');
			return $this->load->view('extension/module/helloworld', $data);
		}
	}
}

Mostly same conventions to follow as for the admin controller as we define above, here we need to pass the $setting in the index method and all values and data of module is available for your in $setting, if you are confused just do the print_r($setting) and you will get all the details data of the module. Here we check if the module is active and just show the title that we entered in the backend.

View section is also pretty simple in the frontend. Go to catalog >> view >> theme >> default >> template >> extension >> module >> helloworld.twig and enter the code below:

<div>
  {% if html %}
      <h2>{{ html }}</h2>
  {% endif %}
</div>

It check if the html is not empty and if not empty then show the html content.

Now all of our code is ready, now you can show it in your desired layout as per requirement. If you are confused about how to install the module and set the configuration then this video helps.

Comment below or let us know if you have any questions or suggestions.

Workflow or markup to make hello world module – OpenCart Module Development

When we created the hello world module then it will be like as shown below:

Hello World Module in Extension’s Module

hello world module opencart extension listing

Installing Hello World Module

Click on the green (install) button, then click edit blue button. You will see a form to insert the hello world text.

Hello World Module form

helloworld form opencart module development

Enter the hello world text and select the status to enabled and click the save button. As Opencart can have unlimited module instance, so we can have multiple instances of the hello world

Set up layout and position for Hello World Module

To setup layout and position, go to Design >> Layout, edit Information layout then add the hello world module to the column left.

hello world module layout and position

Show up in Front/Presentation side

As we added to the column left of the information page, let’s go to the front page about us page URL.
/index.php?route=information/information&information_id=4

hello world front presentaion opencart

Files and folder creation

  • Making language file in admin/ for Hello World Module
  • Making the controller file in admin/ for Hello World Module
  • Making view file in admin/ for Hello World Module
  • Making language file in catalog/ for Hello World Module
  • Making the controller file in catalog/ for Hello World Module
  • Making view file in catalog/ for Hello World Module
Hello world opencart files and folders structure

Now go to full details to create a hello world module in OpenCart

Thanking you
webocreation.com@gmail.com
twitter
:@rupaknpl

youtube

 : onlinegyannepal

https://webocreation.com

Opencart 3 OCMOD coding tutorial

In this tutorial, we are showing you how to write code in OCMOD and modify the core files of OpenCart. Here we will show the flows that happened when someone uploads the ***.ocmod.zip file, then create an install.xml file to show the module link in the left column and give you details of Ocmod documentation in Opencart 3. For Opencart 4 OCMOD tutorial click here

As per the core code when you upload the ***.ocmod.zip folder from Extensions >> Installer, the following things will happen:

  1. Check if the user has permission. You will get an error like:
    “Warning: You do not have permission to modify modifications!”
  2. Check if there is an install temporary folder zip already there.
  3. If it found the file and the file created time is less than 5 seconds then it tries to unlink or remove the file, if it cannot remove the file then it throws an error saying:
    “Extension installation taking place please wait a few seconds before trying to install!”
  4. It checks whether the uploaded zip file ends with .ocmod.zip
  5. It checks if there are any other file uploading errors, UPLOAD_ERR_OK: Value: 0; There is no error, and the file uploaded with success. If there is any error it will show errors like:
    “File could not be uploaded!”
  6. If everything is good then it creates a .tmp file and performs function move_uploaded_file.
  7. Then it adds the logs in the database table oc_extension_install with the name ***.ocmod.zip and the extension download id. “oc_” is the database prefix.
  8. Then it starts the installation, from the controller “ControllerMarketplaceInstall”, it makes sure the file name is stored in the session. If the file is not in that session then it shows an error like this:
    “File could not be found!”
  9. Then it starts unzipping the ***.ocmod.zip and if it cannot unzip the ocmod.zip file then it shows an error like:
    “Zip file could not be opened!”
  10. After unzipping it checks whether the unzip folder contains “upload/” or not, likewise, it checks for the allowed directories to be written or not. Opencart allows the following directories only:
    • ‘admin/controller/extension/’,
      ‘admin/language/’,
      ‘admin/model/extension/’,
      ‘admin/view/image/’,
      ‘admin/view/javascript/’,
      ‘admin/view/stylesheet/’,
      ‘admin/view/template/extension/’,
      ‘catalog/controller/extension/’,
      ‘catalog/language/’,
      ‘catalog/model/extension/’,
      ‘catalog/view/javascript/’,
      ‘catalog/view/theme/’,
      ‘system/config/’,
      ‘system/library/’,
      ‘image/catalog/’
  11. So while creating a custom opencart module better to work on these folders only. If you put it in another folder then it may give you the following error:
    “The directory %s is not allowed to be written to!”
  12. It checks for the directory structure of the zip and whether it matches with the Opencart directory structure.
  13. Then it will insert in the database table oc_extension_path with extension install id.
  14. Then it will start installing the /install.xml, if an XML file exists then it is put into the database. It checks for the “code” name in the XML and checks if the values already exist in the database. If everything is good then it inserts into the database table oc_modification with extension_install_id, name, code, author, version, link, XML, status, and date_added.
  15. Then it unlinks or removes the temporary folder.
  16. Finally, it gives the success message.

With the flow steps above the folder structure for the ocmod.zip is install.xml and upload. Inside the upload/ folder put the OpenCart folder and files.

In the install.xml it should be something like where the ******* is your custom thing.

ocmod code starter
<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>*******</name>
    <version>*******</version>
    <author>*******</author>
    <link>*******</link>
    <code>*******</code>
    <description>*******</description>
    <file path="*******">
        <operation>
            <search><![CDATA[ ******* ]]></search>
            <add position="*******"><![CDATA[*******]]></add>
        </operation>
    </file>
</modification>

Don’t forget <code>, although it is not mentioned in the Modification system documentation https://github.com/opencart/opencart/wiki/Modification-System

You can use multiple file operations. There are two operations search and add. With the Add operation, you can replace, add before, or add after.

<file path="">
    <operation>
        <search><![CDATA[]]></search>
        <add position=""><![CDATA[]]></add>
    </operation>
</file>

Now check out the previous blog posts where we have listed all the documentation of OCMOD.

While zipping the folder zip the install.xml and upload/ folder, not the main folder. install.xml is not mandatory.

If you are trying to create a table or insert data in the table then you need to create the install method in your controller. Like:

module install database

In the install method, you can implement logic as needed for your module when it is installed.

//Check it in admin/controller/extension/extension/module.php install method.
// Call install method if it exists
$this->load->controller('extension/module/' . $this->request->get['extension'] . '/install');

Similarly, you can implement the logic for the uninstalling method when it is uninstalled.

We created a free module with OCMOD to show the Module link in the left menu with the following XML:

<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>Show Module Link At Left Menu</name>
    <version>3.0</version>
    <author>Rupak Nepali</author>
    <link>https://webocreation.com</link>
    <code>webocreation_show_module_link_at_left_menu</code>
    <description>Show module link at left menu</description>
    <file path="admin/controller/common/column_left.php">
        <operation>
            <search><![CDATA[ if ($this->user->hasPermission('access', 'marketplace/extension')) { ]]></search>
            <add position="after"><![CDATA[
                $marketplace[] = array(
                    'name'     => "Modules",
                    'href'     => $this->url->link('marketplace/extension&type=module', 'user_token=' . $this->session->data['user_token'], true),
                    'children' => array()
                );
            ]]></add>
        </operation>
    </file>
</modification>

Steps for making changes to the core files of OpenCart

  1. In your local make the changes in the core of the files and keep track of the files
  2. Then create the install.xml and add those changes in install.xml
  3. Then remove the changes of the core files that you make the changes.
  4. Then zip it with ***.ocmod.zip and upload in Extensions >> Installer
  5. Then clear the cache in Extensions >> Modifications
  6. You are set.

Testing Tips for the Developer

Testing is hard for OCMOD changes if you have to change in XML, zip, upload from the installer, and clear in modifications. So the tip for developers is they can place the install.xml in the system/ folder (not sure if it is supported in Opencart version 3.0.3.2), then make changes in the install.xml and you don’t need to zip and upload, you can clear in modifications and you can check the changes. If you don’t want to clear the cache in modifications then you can go through this blog Opencart cache clear.

If their search code is not found then it shows an error like the below in the Ocmod log:

MOD: 
FILE: admin/controller/common/column_left.php
CODE: if ($this->user('access', 'marketplace/modification')) {
NOT FOUND - OPERATIONS ABORTED!

The Search Code provides the following attributes:

  • trim=”(true|false)”
  • regex=”(true|false)”
  • index=”(number)”

The add code provides the following attributes:

  • trim=”(true|false)”
  • position=”(replace|before|after)”
  • offset=”(number)”

Other you can read at https://webocreation.com/ocmod-documentation/

Let us know if you have any suggestions or questions.

Sidebar Search Opencart module for free version 2

We are publishing another free Opencart module “Sidebar Search module” and we made this for OpenCart version 2.0.3.1. No files are overridden, you can enable it and disable it whenever you like from the admin section.

Output after installing the module in the home page’s right column is shown as in the image below:

sidebar search opencart module free
sidebar search opencart module free

Although the search is available at the header section so it is useless to use at default theme but you can use it for the customized theme and I will make another search module soon which will include all search functionality as the main search page. For now, enjoy this normal search opencart free module. You can see how I copied the header search section and show it as a module in the side search box. You can show anywhere you like as this is a module so you can show in the left column, right column or top content or bottom content.

Download Sidebar shopping cart free module from the link below:

Download Sidebar search OpenCart free module

Installation:

  1. Unzip the downloaded folder.
  2. Upload the files in the root folder to your server, no file is overwritten.
  3. Then activate the Search module.

Activating the Sidebar Search module:

  1. After uploading files to servers, it’s time to install Sidebar search module
  2. We are showing the sidebar search at the right column but you can show it wherever you like as this acts as the normal module.
  3. Go to Admin section
  4. Then click on Extensions on the left menu
  5. After that Click Modules and go to “Search” in the modules list
  6. Then click the green button to install the module (see the image below)
installation_of_module
installation_of_module

Then click the blue edit button After that, you will see the form which has the status field, select “Enabled” and then click the Save button. Your module is active and is ready to use in the layout.

Setup layout for the sidebar search module at home page:

  1. From the admin section go to System >> Design >> Layouts.
  2. You will see a list of layouts, from which edit the “Home” layout.
  3. Then click Blue add the button to add rows at module section which is shown in the image below:
siderbar shopping cart installation
siderbar_shopping_cart_installation

Second, you choose the Search in module column and Column right in the Position column and insert the sort order as required. Then click save button

Your custom sidebar search module is showing in the right column of the homepage. Likewise, you can show in many other layouts and pages.

Codes in search modules controller:

<?php
class ControllerModuleSearch extends Controller {
    public function index() {
        $this->load->language('module/search');
        $data['heading_title'] = $this->language->get('heading_title');
        
        $data['search'] = $this->load->controller('common/search');

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/search.tpl')) {
            return $this->load->view($this->config->get('config_template') . '/template/module/search.tpl', $data);
        } else {
            return $this->load->view('default/template/module/search.tpl', $data);
        }
    }
}

The main role player code here is

$data['search'] = $this->load->controller('common/search');

Code of search modules in language section:

<?php
// Heading
$_['heading_title'] = 'Search';

Code of search modules in theme (presentation layer):

<h3><?php echo $heading_title; ?></h3>
<hr>
<div class="row">
    <div class="product-layout col-lg-12 col-md-12 col-sm-12 col-xs-12">
        <header><?php echo $search; ?></header>
    </div>
</div>
<hr>

Let me know if you get any problem with performing tasks in the comment so that I can help if you have any.

Thanks
Rupak Nepali