Home Blog Page 21

Show only subcategories on category page OpenCart 2.0 free module

We make another free module today “Show only subcategories on category page OpenCart 2.0 free module” when enabled to category page then you will be able to see sub-categories of the active Category as a heading.

Download “Show only subcategories on category page OpenCart 2.0 free module” from the link below:
Download Show only subcategories on category page OpenCart 2.0 free module
Download Show only subcategories on category page OpenCart 2.2 free module

The module will look like below:

Only Sub Categories at Product Page
Only Sub Categories at Product Page

Admin section will look like:

Only Sub Categories at Category Page admin
Only Sub Categories at Category Page admin

This is an extension for opencart 2.0 and 2.2 that I modify the Category module so it only displays the current top-level category page’s sub-categories. For example, if I am on the “Laptops & Desktops” category page, the sidebar module would only list the sub-categories associated with “Laptops & Desktops” category, such as “Macs” and “PCs” with the main heading “Laptops & Desktops” (And not list or show any of the other top-level categories).

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 Only Sub-Categories module.

Activating the Only Sub-Categories module:

  1. After uploading files to servers, it’s time to install Only Sub-Categories module
  2. We are showing the Only Sub-Categories module at the right or left column of the Category page (Category Layout).
  3. Go to Admin section
  4. Then click on Extensions on the left menu
  5. After that Click Modules and go to Only Sub-Categories in the modules list
  6. Then click the Green button for the Only Sub-Categories to install the module (see the image below)
  7. Then click blue edit button
  8. After that, you will see the form which has the status field, select Enabled and then click the Save button.
  9. Your module is active and is ready to use in the layout.

Setup layout for the sidebar Only Sub-Categories module at the left column of category page:

  1. From the admin section go to System >> Design >> Layouts.
  2. You will see a list of layouts, from which edit the Category layout.
  3. Then click Blue add the button to add rows at the module section which is shown in the image below:
  4. Second, you choose the Only Sub-Categories in module column and Column left in the Position column and insert the sort order as required.
  5. Then click save button

Your custom category page is ready with the Only Sub-Categories module in the left column.

Regex to find the four sequential characters in PHP

Need to check if a string contains four sequential characters or consecutive characters/strings or identical letters/numbers/string/characters in PHP then following regex and code can be useful for you. I tested it with following code and regex is generated from

<?php
$re = '/(abcd|bcde|cdef|defg|efgh|fghi|ghij|hijk|ijkl|jklm|klmn|lmno|mnop|nopq|opqr|pqrs|qrst|rstu|stuv|tuvw|uvwx|vwxy|wxyz)+/xi';
$str = 'rupakabcd test';
if(preg_match_all($re, $str, $matches)){
  echo "Contains sequential characters";
}else{
  echo "Does not contain sequential characters";
}

If you wanted to check case sensitive then remove ‘i’ from $re variable at the end.

Comment if you find any easy way to make it works.

Regex to find identical characters:

(\w)(\1+){3}

$re = '/(\w)(\1+){3}/i';
$str = 'aaaa
rrrr
rupak
rupakaaaaarrr';

preg_match_all($re, $str, $matches);

// Print the entire match result
print_r($matches);

Regex to find identical numbers:
(\d)\1{3,}

$re = '/(\d)\1{3,}/';
$str = '123452222222222222
1234
1111
12345
654128
45721111572000004520
aaaa
rupak
';

preg_match_all($re, $str, $matches);

// Print the entire match result
print_r($matches);

Regex to find five sequential numbers:

(?: 0(?=1|\b)| 1(?=2|\b)| 2(?=3|\b)|  3(?=4|\b)|  4(?=5|\b)|  5(?=6|\b)|  6(?=7|\b)|  7(?=8|\b)|  8(?=9|\b)|  9\b  ){5}

$re = '/(?: 0(?=1|\b)| 1(?=2|\b)| 2(?=3|\b)|  3(?=4|\b)|  4(?=5|\b)|  5(?=6|\b)|  
6(?=7|\b)|  7(?=8|\b)|  8(?=9|\b)|  9\b  ){5}/x';
$str = '123 321 56789 890123 321098 134 333 421 12345 6789 
15246
1234567890
67890
12345
23456
34567
456789
56789
';

preg_match_all($re, $str, $matches);

// Print the entire match result
print_r($matches);

Dropdown Quantity of Product in Cart Page Opencart 2.2

This is an Opencart guide to create a dropdown of the quantity field of product in Cart Page Opencart 2.2.

Download Dropdown Quantity of Product in Cart Page Opencart 2.2

Features:

  • Instead of the textbox, select box shows in the quantity field of Cart.
  • When you change quantity options then the cart will update automatically.
  • Also, have a delete button.

First, open system\library\cart\cart.php and find the following lines of code:

$product_data[] = array(
					'cart_id'         => $cart['cart_id'],
					'product_id'      => $product_query->row['product_id'],

Below these lines of code add the following line:

'product_quantity'           => $product_query->row['quantity'],

Second open controller catalog\controller\checkout\cart.php and find the following lines of code:

$data['products'][] = array(
					'cart_id'   => $product['cart_id'],

Below these lines of codes add the following line:

'product_quantity'=>$product['product_quantity'],

At last find following lines of code at catalog/view/theme/YOUR_ACTIVATED_THEME/template/checkout/cart.tpl

<td class="text-left">
                      <div class="input-group btn-block" style="max-width: 200px;">
                          <input type="text" name="quantity[<?php echo $product['cart_id']; ?>]"
                                 value="<?php echo $product['quantity']; ?>" size="1" class="form-control"/>
                    <span class="input-group-btn">
                    <button type="submit" data-toggle="tooltip" title="<?php echo $button_update; ?>"
                            class="btn btn-primary"><i class="fa fa-refresh"></i></button>
                    <button type="button" data-toggle="tooltip" title="<?php echo $button_remove; ?>"
                            class="btn btn-danger" onclick="cart.remove('<?php echo $product['cart_id']; ?>');"><i
                                class="fa fa-times-circle"></i></button>
                    </span></div>
                  </td>

Replace with the following code:

  <!--Changes done-->
                  <td class="text-left">
                      <div class="input-group btn-block" style="max-width: 200px;">
                          <select name="quantity[<?php echo $product['cart_id']; ?>]"
                                  onchange='this.form.submit()'>
                              <?php for($cp=1; $cp<=$product['product_quantity']; $cp++){ ?>
                              <option
                              <?php if($product['quantity']==$cp){ echo "selected"; } ?>
                              value="<?php echo $cp; ?>"><?php echo $cp; ?></option>
                              <?php } ?>
                          </select>
        <span class="input-group-btn">
        <button type="button" data-toggle="tooltip" title="<?php echo $button_remove; ?>"
                class="btn btn-danger" onclick="cart.remove('<?php echo $product['cart_id']; ?>');"><i
                    class="fa fa-times-circle"></i></button>
        </span>
                      </div>
                  </td>
                  <!--End of Changes done-->

Output:

dropdown_in_cart

Please bear with that CSS and hope you will make changes to that CSS as per your theme.
Similarly, we would have provided OCMOD, but because of laziness, we always go through logics :).

Enjoy it, hope we will soon launch OCMOD for all of you.

Thanks
Rupak Nepali

Special Characters are not stored properly in Opencart- Ecommerce

Today something went wrong with encoding in opencart – we cannot save the city with special language characters, like raga, but found out that it is a database field error.

When we try to insert raga, it is inserted as R?ga. ? marks in place of special characters

So we have to find out why this is happening, we check the code all working fine and at last, saw the database table field have a collation of latin1_bin so we change it to utf8_bin and the special character is saved on the database and the same are shown correctly.

So while making the database table keep these things into mind, if you have to save multi-language then utf8_bin is to be set on the collation

special character in opencart
special character in opencart

 Let us know if you have questions or concerns so that we can help you out, similarly, let us know if there are another best solutions. Till then please subscribe to our YouTube Channel for Opencart video tutorials. You can also find us on Twitter and Facebook.

The directory catalog/controller/product is not allowed to be written to – Opencart error

Opencart error directory not allowed

When you are installing the extension, you go to admin >> extensions >> installer and click the upload button and select the extension ocmod.zip file but you got the following error like “The directory catalog/controller/product is not allowed to be written to – Opencart error”. The way to solve it is to add the path at admin\controller\marketplace\install.php

Here in the example, the path is catalog/controller/product/ so we needed to add at

// A list of allowed directories to be written to
$allowed = array(
   '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/',
   'catalog/controller/product/' 
);

Whatever error path you get, you need to add here to install successfully. But the best practice is to stick to the provided folders only if you need to manage multiple folders than manage subfolders within them.

Thanks
Rupak Nepali

Admin Catalog Product listing default sort order to latest inserted product

OpenCart Product listing default sort order is as per product name, and you can sort them with product name ASC or DESC, Model ASC or DESC, price ASC or DESC, quantity ASC or DESC and Status ASC or DESC just by clicking on the listing of the table heading.

Opencart Product listing by product_id

But if you want to sort as per the latest inserted product then you need to do some code changes in default file which is not good but requirements always come first. (OcMod coming soon)

Find the following lines of code in admin\controller\catalog\product.php:

if (isset($this->request->get['sort'])) {
    $sort = $this->request->get['sort'];
} else {
    $sort = 'pd.name';
}

if (isset($this->request->get['order'])) {
    $order = $this->request->get['order'];
} else {
    $order = 'ASC';
}

Replace with the following lines of code:

if (isset($this->request->get['sort'])) {
    $sort = $this->request->get['sort'];
} else {
    $sort = 'pd.product_id';
}

if (isset($this->request->get['order'])) {
    $order = $this->request->get['order'];
} else {
    $order = 'DESC';
}

With this, the product listing will be listed with the latest product inserted by default, and click on table titles as per your req

Twig Template coming in OpenCart 2.3

In the upcoming OpenCart 2.3, both template engines will be supported PHP template and twig engine.

OpenCart will allow you to override all of the templates that are used to produce HTML markup so that you can fully control the markup that is being outputted within a custom theme. There are templates for each page element ranging from the high-level HTML to small fields.

twig template opencart

What is Twig?

Twig is a modern template engine for PHP

  • Fast: Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum.
  • Secure: Twig has a sandbox mode to evaluate the untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.
  • Flexible: Twig is powered by a flexible lexer and parser. This allows the developer to define its own custom tags and filters, and create its own DSL.

You can find the Twig website at https://twig.symfony.com/
Documentation: https://twig.symfony.com/doc/3.x/

You can update your preexisting OpenCart theme by replacing PHP codes to twig codes and changing .tpl template file extension to .twig extension.

  • .tpl will use the PHP engine
  • .twig will use the Twig engine

Below is one example of regular expression code to help with your PHP IDE to mass search and replace basic PHP syntax with Twig syntax.

<?php echo $var; ?>

<\?php echo [$](\w*\b)[;] \?\>

{{ $1 }}

<?php echo $error_name[$language['language_id']]; ?>

<\?php\s+echo\s+[$](\w+)\[[$](.*)\[\'(.*)\'\]\]\; \?\>

{{ $1[$2.$3] }}

All details are provided at https://github.com/opencart/opencart/wiki/Upgrading-themes-from-2.3-to-2.3

Now in template section you can write following :

To show header section: {{ header }}

To show bottom content: {{ content_bottom }}

Similarly, {{ content_top }}, {{ column_right }}, {{ column_left }}, {{ footer }}

Previously breadcrumb codes at .tpl files used to look like below:

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

But now with .twig it looks like below:

 <ul class="breadcrumb">
    {% for breadcrumb in breadcrumbs %}
    <li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
    {% endfor %}
  </ul>

Thus, it seems twig consist features like: concise, template oriented syntax, full featured, easy to learn, extensibility, unit tested, documented, secure, clean error messages and fast which I believe will improve development speed.

Thanks for the OpenCart team on using Twig.

Feedback or Testimonials Module for Opencart 2.2 for Free

Feedback or Testimonial Module is the module for Opencart by which customers can provide their feedback about the site or product or any services. We were encouraged to develop it because there is a review system for the products but not for the site and services so we made this feedback or testimonial module.

INSTALLATION OF FILES:

  1. Unzip the zip file where you will find “Testimonial-OpenCart-Module-Free-master” folder.
  2. “Testimonial-OpenCart-Module-Free-master” folder contains “admin” and “catalog” folder
  3. Upload the files and folders of the admin and catalog folder to your OpenCart root folder. You can use FTP or SFTP to upload these files and folders.
  4. After completing uploading, login to the admin section, go to Extensions > Modules.
  5. Go to “Testimonial” and click the green install button.
    install_opencart_module_webocreation
  6. Our Testimonial module is installed. Now click blue edit button. If this is first time then you will see like the following image to install the database.
    database-not-found
  7. Click the Install Database button and three tables are created in database. As following sql queries are run, for easy installation I created this way.

    CREATE TABLE oc_testimonial ( testimonial_id int(11) NOT NULL, name varchar(64) NOT NULL, status tinyint(1) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE oc_testimonial_image ( testimonial_image_id int(11) NOT NULL, testimonial_id int(11) NOT NULL, link varchar(255) NOT NULL, image varchar(255) NOT NULL, sort_order int(3) NOT NULL DEFAULT '0' ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE oc_testimonial_image_description ( testimonial_image_id int(11) NOT NULL, language_id int(11) NOT NULL, testimonial_id int(11) NOT NULL, title varchar(64) NOT NULL, message text NOT NULL, name varchar(250) NOT NULL, position varchar(250) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; ALTER TABLE oc_testimonial ADD PRIMARY KEY (testimonial_id); ALTER TABLE oc_testimonial_image ADD PRIMARY KEY (testimonial_image_id); ALTER TABLE oc_testimonial_image_description ADD PRIMARY KEY (testimonial_image_id,language_id); ALTER TABLE oc_testimonial MODIFY testimonial_id int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; ALTER TABLE oc_testimonial_image MODIFY testimonial_image_id int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=144;
  8. Wait did you see Permission Denied message. Then it means you do not have permission to access this page, please refer to your system administrator. If you are administrator then Go to the System >> Users >> User Groups and edit the “Administrator” or related user group  and then check checkbox “module/testimonial” and “design/testimonial” in both Access Permission and Modify Permission as in the figure. For easiness you can click “Select All” in both permission and grant all access ( Do this only for top administrator).
    user-group-grant-permission
  9. Once you grant permission, you will be able install the database and install the module. Now edit the “Testimonial” module and click the “Install Database” blue button.
  10. Now you will see as following image where you will insert the Testimonial, click the Insert Testimonial button.
    insert-testimonial
  11. You can insert multiple list of testimonial so you can show different testimonials in different layouts.
    insert-testimonials
  12. Now start to inserting testimonials by clicking the blue button and see the image what goes where:
    testimonial-insertion-form
  13. After inserting these you choose that into the testimonial module. Go to Admin>> Extensions>> Modules >> Testimonial >> Edit
  14. Now activate Testimonial module
    activate-module-testimonial
  15. Now go to Admin >> Design >> Layout, then edit the “Category” from the list. We are showing our testimonial module at category left column.
    activate-layout-section
  16. Now view any category page and you will see like the image below:
    front-end
  17. presentation-layer
  18. You are ready to go live.
  19. If you feel like you have to change the CSS then you can edit catalog/view/theme/default/module/testimonial.tpl. We integrate the CSS in the same file so that it does not conflict with others.
  20. If you want to change animation then you can set at catalog/view/theme/default/module/testimonial.tpl

<script type="text/javascript">
    $('#testimonial<?php echo $module; ?>').owlCarousel({ 
        items: 6, 
        autoPlay: 5000, 
        singleItem: true, 
        navigation: false, 
        pagination: false,     
        rtl:true, 
        transitionStyle: 'fade' 
    });
</script>

Other than that if you need help then please comment below.

Thanks
Rupak Nepali

COPYRIGHT:

This module code is the intellectual property of the designers involved in its creation. As an Opensource code you are entitled to use it freely and modify it if you wish but please keep the credits intact.

Enjoy!

How to pull products JSON through API in Opencart?

In this tutorial, we show how to pull products in JSON format through API in Opencart. First, read the post below to understand the OpenCart API:

We take an example between two servers one from https://webocreation.com/nepalbuddha which acts as Server Responder of API which is built in OpenCart and https://tuliprsdynasty.com/api/ as the requestor.

Opencart API explained

Responding server

OpenCart does not provide API to show the products by default so we need to make some changes in responding server to show all products. For that in your responding server go to catalog/controller/api/ and create product.php and paste following lines of code:

<?php
class ControllerApiProduct extends Controller
{
    public function index()
    {
        $this->load->language('api/cart');
        $this->load->model('catalog/product');
        $this->load->model('tool/image');
        $json = array();
        $json['products'] = array();
        $filter_data = array();
        $results = $this->model_catalog_product->getProducts($filter_data);
        foreach ($results as $result) {
            if ($result['image']) {
                $image = $this->model_tool_image->resize($result['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_height'));
            } else {
                $image = $this->model_tool_image->resize('placeholder.png', $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_height'));
            }
            if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
            } else {
                $price = false;
            }
            if ((float) $result['special']) {
                $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
            } else {
                $special = false;
            }
            if ($this->config->get('config_tax')) {
                $tax = $this->currency->format((float) $result['special'] ? $result['special'] : $result['price'], $this->session->data['currency']);
            } else {
                $tax = false;
            }
            if ($this->config->get('config_review_status')) {
                $rating = (int) $result['rating'];
            } else {
                $rating = false;
            }
            $data['products'][] = array(
                'product_id' => $result['product_id'],
                'thumb' => $image,
                'name' => $result['name'],
                'description' => utf8_substr(trim(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8'))), 0, $this->config->get('theme_' . $this->config->get('config_theme') . '_product_description_length')) . '..',
                'price' => $price,
                'special' => $special,
                'tax' => $tax,
                'minimum' => $result['minimum'] > 0 ? $result['minimum'] : 1,
                'rating' => $result['rating'],
                'href' => $this->url->link('product/product', 'product_id=' . $result['product_id']),
            );
        }
        $json['products'] = $data['products'];
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}

With the above code it will provide you directly accessing API URL index.php?route=api/product. As per our example, it is https://webocreation.com/nepalbuddha/index.php?route=api/product. Here we did not do any authentication and authorization. It directly shows all products whoever is called from that URL. In our upcoming post, we will show how to show categories to API users only.

Requesting server

In your requesting server, create a file lets say apiproducts.php, as per our example let’s say we create https://tuliprsdynasty.com/api/apiproducts.php In this file let’s make a CURL request to the get the products: https://webocreation.com/nepalbuddha/index.php?route=api/product. Following is the code:

<?php
$url = "https://webocreation.com/nepalbuddha";
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $url . "/index.php?route=api%2Fproduct",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache",
    ),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}

Finally, the response you get will be like below:

{
    "products": [{
        "product_id": "30",
        "thumb": "https:\/\/webocreation.com\/nepalbuddha\/image\/cache\/catalog\/demo\/canon_eos_5d_1-228x228.jpg",
        "name": "Canon EOS 5D",
        "description": "Canon's press material for the EOS 5D states that it 'defines (a) new D-SLR category', while we're n..",
        "price": "$122.00",
        "special": "$98.00",
        "tax": "$80.00",
        "minimum": "1",
        "rating": 0,
        "href": "https:\/\/webocreation.com\/nepalbuddha\/index.php?route=product\/product&product_id=30"
    }, {
        "product_id": "47",
        "thumb": "https:\/\/webocreation.com\/nepalbuddha\/image\/cache\/catalog\/demo\/hp_1-228x228.jpg",
        "name": "HP LP3065",
        "description": "Stop your co-workers in their tracks with the stunning new 30-inch diagonal HP LP3065 Flat Panel Mon..",
        "price": "$122.00",
        "special": false,
        "tax": "$100.00",
        "minimum": "1",
        "rating": 0,
        "href": "https:\/\/webocreation.com\/nepalbuddha\/index.php?route=product\/product&product_id=47"
    }]
}

As per our API set up, it just returns product_id, thumb, name, description, price, special, tax, minimum, rating, and link of the product. If you want to make changes then you have to make changes in catalog/controller/api/product.php as per your need. In this way, you can retrieve all products in JSON format through API.

You can check following Opencart API related posts:

Please don’t forget to post your questions or comments so that we can add extra topics. Likewise, you can follow us at our twitter account @rupaknpl and subscribe to our YouTube channel for Opencart tutorials.

OpenCart API documentation to create, read, query, update, and upsert

The OpenCart API allows your application to access current data within OpenCart through the API, several common operations can be performed. Operations include:

  • create — Creates with the specified parameters.
    For example, you can add products to the cart as given by OpenCart API post request of products or product_id at
    /index.php?route=api/cart/add
  • read — Retrieves information about the specified object.
    For example, you can retrieve the shipping methods with the endpoint: index.php?route=api/shipping/methods
  • query — Retrieves objects that match specified criteria.
  • update — Updates elements of an existing object.
  • upsert — Updates elements of an existing object if it exists. If the object does not exist, one is created using the supplied parameters.

Developers must authenticate with the API before issuing requests.

Some considerations must be taken while performing requests. When performing update requests, only the fields specified in the request are updated, and all others are left unchanged. If a required field is cleared during an update, the request will be declined.

Request Format

All requests:

  • Must use either HTTP GET or POST
  • Must pass credentials in an HTTP Authorization header – or – in the body of a POST request

Authentication and Request Format of OpenCart API:

Authentication requests sent to the OpenCart API URL:

  1. it must be made via SSL encrypted connection
  2. Must use HTTP POST
  3. Must contain usernameand key for the Opencart user account that will be submitting API requests

Login requests that meet these criteria will be granted an api_token id.

You can see the API username and API key at Admin >> System >> Users >> API

Both UserNAME and API key are unique to individual users. API Token ID is valid for 60 minutes. In contrast, user keys are valid indefinitely which you can regenerate as needed.

Request Parameters

ParameterRequiredDescription
usernameXThe API username
keyXThe API keys generated for the API user

CURL login example:

<?php
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://webocreation.com/nepalbuddha/index.php?route=api%2Flogin",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "key=ijLJxZa1kUO8DP4gp0iSHewnDN8zpf7T4c0d8qE3OBZi5sJnkWmi5GQ1UcGR6SttzCtHXv80ImiBGz8saVx5JBrQf5zTmetuSLGjLZNiLDoOWY0zpDQIHWWyh0mr4WATp4HJ3knAiV3G8AE6km0BgY4liu5Uik5w2FKFqkZHldVNOoDaKyOJhp2bCeVqxbDHJpHlv2lECKIBsglLFSZmUmv1e7rpWnyi7HCzyX14Odpq37j4coM5iuspzm3dwloX&username=rupak",
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache",
        "content-type: application/x-www-form-urlencoded",
        "postman-token: 60329eeb-62ad-78e6-f564-486a6a1fe051"
    ),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}

If authentication was successful, a 32-character hexadecimal API token will be returned in the following format:

{"success":"Success: API session successfully started!","api_token":"10f6607afd57b954a853f7ce29"}

Example Curl POST Request in OpenCart API:

curl -X POST \
  'https://webocreation.com/nepalbuddha/index.php?route=api%2Flogin' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/x-www-form-urlencoded' \
  -H 'postman-token: 2ef6e7f4-84d1-28ae-84b0-ae2dcebeab2f' \
  -d 'key=ijLJxZa1kUO8DP4gp0iSHewnDN8zpf7T4c0d8qE3OBZi5sJnkWmi5GQ1UcGR6SttzCtHXv80ImiBGz8saVx5JBrQf5zTmetuSLGjLZNiLDoOWY0zpDQIHWWyh0mr4WATp4HJ3knAiV3G8AE6km0BgY4liu5Uik5w2FKFqkZHldVNOoDaKyOJhp2bCeVqxbDHJpHlv2lECKIBsglLFSZmUmv1e7rpWnyi7HCzyX14Odpq37j4coM5iuspzm3dwloX&username=rupak'

Example curl GET request in Opencart API:

curl -X GET \
'https://webocreation.com/nepalbuddha/index.php?route=api%2Fcart%2Fproducts&api_token=10f6607afd57b954a853f7ce29' \
-H 'cache-control: no-cache' \
-H 'postman-token: 969b0a8f-aa76-5ec5-10f5-a5f768a2868d'

Here api_token=YOUR_TOKEN_VALUE

It will give the following results when there are no products:

{
    "products": [],
    "vouchers": [],
    "totals": [
        {
            "title": "Sub-Total",
            "text": "$0.00"
        },
        {
            "title": "Total",
            "text": "$0.00"
        }
    ]
}

Similarly, you can use the following API end points:

  • index.php?route=api/login
  • index.php?route=api/cart/add
  • index.php?route=api/cart/edit
  • index.php?route=api/cart/remove
  • index.php?route=api/cart/products
  • index.php?route=api/coupon
  • index.php?route=api/currency
  • index.php?route=api/customer
  • index.php?route=api/order/add
  • index.php?route=api/order/edit
  • index.php?route=api/order/delete
  • index.php?route=api/order/info
  • index.php?route=api/order/history
  • index.php?route=api/payment/address
  • index.php?route=api/payment/methods
  • index.php?route=api/payment/method
  • index.php?route=api/reward
  • index.php?route=api/reward/maximum
  • index.php?route=api/reward/available
  • index.php?route=api/shipping/address
  • index.php?route=api/shipping/methods
  • index.php?route=api/shipping/method
  • index.php?route=api/voucher
  • index.php?route=api/voucher/add

Above all, please see this post, how you can get all products through API in OpenCart. Please let us know if you have any questions, suggestions and follow us at twitter @rupaknpl and subscribe to our youtube channel Opencart tutorials where you can see OpenCart tutorials for beginners to advance programmers.

OpenCart error FTP needs to be enabled in the settings

This is a solution for the OpenCart error FTP needs to be enabled in the settings. Navigate to System >> Settings >> then edit store where you want to enable the FTP

Then click FTP tab

how to enable ftp in opencart
  • Enter FTP host usually “localhost”, but make sure it is correct from your hosting.
  • Enter port usually “21”, but make sure it is correct from your hosting
  • Enter FTP username
  • Enter FTP password
  • Enter the root folder path of your hosting
  • Then choose Yes to enable FTP
  • Finally, save  it

You are set and your FTP is enabled.

Host your NextJs project for free, local to GitHub to hosting, continuous deployment setting

In this post, we are showing you how to create and host the NextJs project for free with GitHub flow to hosting and add your domain name. The NextJs is a react framework that is production-ready, pre-rendered, and light-weight apps, the Jamstack(JavaScript, APIs, and markup stack), SEO-friendly, PWAs, and mobile-ready. We set up a GitHub project, then set up the local environment, and then setup Vercel hosting where the master branch is continuously deployed. A domain is added for the master branch and you can add the dev and test environment by creating the branches in the Github project.

  • First, register your domain name. It can cost you around $8-$10 and some countries provide it free also, like in Nepal if you register as per your name then it is free like mine is rupaknepali.com.np.
  • Second, create a GitHub account if you don’t have by going to https://github.com/join and then create a repository in GitHub. In the below example the repository name is “ebookdesign”
Github repository creation
  • Setup a local development environment. Install NodeJs, Github, IDE(we use Visual Studio code),
  • Now, in the terminal create a folder like for us we create “ebookdesign“, go or ‘cd’ to the project folder, and clone the GitHub project that we create above in the Github. Use your project URL.
git clone https://github.com/webocreation-rupak/ebookdesign.git .
  • After you cloned it, run following command
npm init -y && npm install --save react react-dom next

This will create the package.son file and install react, react-dom, and next project. Now open the package.json, then remove the following lines of code:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },

Then add following lines of code:

 "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },

Open pages/ folder and create at file named index.js and paste following code:

const Index = () => {
  return (
    <div>
      <h1>Hello World</h1>
    </div>
  );
};
export default Index;

Now open the project and create pages/ folder and public/ folder, the files and folders till now are like below:

Files and folders structure of NextJs

Now in terminal run command

npm run dev

It will start the server on http://localhost:3000 and compile code successfully. You can open the URL http://localhost:3000 in your browser and you can see the “Hello World” page, which means you did all good till now.

Now push this code changes in the github project.

git add . && git commit -m "pages folder and public folder are created" && git push origin master

Now go to https://vercel.com/signup and click the button “Continue with GitHub”. Then you authorize the Vercel to Github.

Authorize Vercel with Github

You will get the popup to enter your mobile number for the verification process. After verification with mobile code, you are redirected to the welcome page where you need to enter your details.

Welcome message of NextJs integration

Import github repository

Importing git repository on NextJs

Enter the URL of your Github repository and click “Continue”

Importing git repository on hosting

Install Vercel to Github and give access to your repositories

Install Vercel on github

Then, in the next screen you can click the deploy the project and if everything is Ok then your project is successfully added.

Successful setup of continuous integrations from github to NextJs

You will get the url like https://ebookdesign.vercel.app/

Now let’s add our domain to the project, for that, go to Settings at the top menu and then in the domain and add the domain name.

Domain name settings in NextJs

https://vercel.com/docs/custom-domains#dns-records

After adding the domain you will get the DNS records which you need to add on your domain registrar.

Domain name delegates

With these changes you can visit through your URL, here we are using dpsignadvertising.com

The easy part using the Vercel, we can create as many demo website as we want, each branch of your Github project. Let create one branch in our local called dev and push it to github and it will automatically show at the hosting.

git checkout -b dev
git add .
git commit -m "Dev branch test"
git push origin dev

Once above command is run, then we will get the “Preview Deployments” like below at Project >> Overview, it gives us the URL like https://ebookdesign-orz1lbra5.vercel.app/

Dev environment setup on NextJs projects

Check the flow diagram:

NextJs local Github Vercel flow

Now you can make changes to the code and start your development. In our upcoming post, we will show you how to show youtube videos, WordPress posts, and texts. Please let us know if you have any questions or concerns. Hope you liked this article, please subscribe to our YouTube Channel for Opencart video tutorials. Find us on Twitter and Facebook.

Separate register form containing email and password only in OpenCart 2.2

We created files that will show the Separate register form page containing email and password only in OpenCart 2.2.
At our server it is working when we run like index.php?route=account/registerb it is showing as the following images:

register-with-different-form

Download code below:

Download Different Register Page Code

Thanks
Rupak Nepali

OCMOD Modification System opencart 2.3 example for Show all products module eCommerce

In this opencart guide, we are showing you the OCMOD Modification System of Opencart 2.3 with an example of the “Show all products module” eCommerce. Opencart 4 OCMOD documentation

Things to take care of while making an OCMOD file:

  1. File extension must be either .ocmod.zip or .ocmod.xml.
  2. Upload from the admin section, Admin>>Extensions >> Extension Installer, Upload the .xomod.zip or .ocmod.xml file from here.

Now go to the following link and download the “Display all Products” module Download shows all products module You will find the following OCMOD example which shows how to show “All Products” links at the top menu bar.  

For example:

<modification>
<version>OpenCart Version 2.2</version>
<vqmver>2.0.0</vqmver>
<author>Rupak Nepali</author>
   <code>List_all_Products</code>
<file name="catalog/view/theme/*/template/common/header.tpl" error="skip">
<operation>
<search position="after"><![CDATA[
<ul class="nav navbar-nav">
]]></search>
<add><![CDATA[
<li><a href="index.php?route=product/allproduct">All Products</a></li>
]]></add>
</operation>
</file>
</modification>

More details at https://github.com/opencart/opencart/wiki/Modification-System OCMOD is a system that allows store owners to be able to modify their store by uploading a compressed file that contains XML, SQL, and PHP files. If an OCMOD is developed correctly it can modify how a user’s OpenCart store works without changing any of the core files. This means that if a modification is removed none of the original OpenCart files need to be restored or fixed.  

OCMOD Files

OCMOD files can be uploaded via the opencart admin under Extensions / Extension Installer For an OCMOD file to be uploaded the file extension must be either .ocmod.zip or .ocmod.xml. This is to avoid none of the OCMOD files from being uploaded to a store user admin.

File Structure

Example file structure for OCMOD compressed files.

  • upload
  • install.sql
  • install.php
  • install.xml

upload

All files under this directory will be uploaded to the directory of your OpenCart installation.

install.sql

Add any create, drop, insert, and update SQL queries here. Make sure each query ends with ;

install.php

If the modification requires any custom PHP code.

install.xml

The XML modification file. You can view the documentation for this system below.

XML

This is the file that creates a virtual copy of any files that require changes. Use this system instead of overwriting any default installation files. Multiple modifications can be applied to the same file. Example OCMOD file:

<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>Modification Default</name>
    <version>1.0</version>
    <author>OpenCart Ltd</author>
    <link>http://www.opencart.com</link>
    <file path="catalog/controller/common/home.php">
        <operation>
            <search><![CDATA[
            $data['column_left'] = $this->load->controller('common/column_left');
            ]]></search>
            <add position="replace"><![CDATA[
            test123
            ]]></add>
        </operation>
    </file>  
</modification>

Tags

File

You can set multiple file locations by spiting up the file locations using commas. The modification system uses the PHP function glob. http://hk1.php.net/manual/en/function.glob.php Example: Direct file path.

<file path="catalog/controller/common/home.php">

Using braces allows for selecting multiple files and not having to repeat the code operation multiple times.

<file path="system/engine/action.php|system/engine/loader.php|system/library/config.php|system/library/language.php">

also allows braces

<file path="system/{engine,library}/{action,loader,config,language}*.php">

please note that all file paths must start with either admin, catalog, or system. you can also use wildcard *

Search

Search code Allowed Attributes

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

Example:

<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>Modification Default</name>
    <version>1.0</version>
    <author>OpenCart Ltd</author>
    <link>http://www.opencart.com</link>
    <file path="catalog/controller/common/home.php">
        <operation>
            <search trim="true|false" index="1"><![CDATA[
            $data['column_left'] = $this->load->controller('common/column_left');
            ]]></search>
            <add position="replace" offset="1"><![CDATA[
            test123
            ]]></add>
        </operation>
    </file>  
</modification>

Add

The code to replace the search with. Allowed Attributes

  • trim=”(true|false)”
  • position=”(Replace|Before|After)”
  • offset=”(number)”

(note position can not be used if regex is set to true in the search attribute). Example

<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>Modification Default</name>
    <version>1.0</version>
    <author>OpenCart Ltd</author>
    <link>http://www.opencart.com</link>
    <file path="catalog/controller/common/home.php">
        <operation>
            <search trim="true|false"><![CDATA[
            $data['column_left'] = $this->load->controller('common/column_left');
            ]]></search>
            <add position="Replace|Before|After" trim="true|false" offset="2"><![CDATA[
            test123
            ]]></add>
        </operation>
    </file>  
</modification>
Regex

Allowed Attributes

  • limit=”(number)”

Example:

<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>Regex Example</name>
    <version>1.0</version>
    <author>OpenCart Ltd</author>
    <link>http://www.opencart.com</link>
    <file path="system/{engine,library}/{action,loader,config,language}*.php">
        <operation>
            <search regex="true" limit="1"><![CDATA[
            ~(require|include)(_once)?\(([^)]+)~
            ]]></search>
            <add><![CDATA[
            $1$2(modification($3)
            ]]></add>
        </operation>
    </file>
</modification>

If you use regex you can not use attributes position, trim or offset as these are handled by the regular expression code you write. The limit attribute is still available. If, for example, you want to change the 3rd ‘foo’ to ‘bar’ on the following line:

lorem ifoopsum foo lor foor ipsum foo dolor foo
^1      ^2      ^3         ^4        ^5

Run:

s/\(.\{-}\zsfoo\)\{3}/bar/

Result:

lorem ifoopsum foo lor barr ipsum foo dolor foo
^1      ^2      ^3=bar     ^4        ^5

You can find more information about the regular expression PHP function OCMOD uses can be found here: http://hk2.php.net/manual/en/function.preg-replace.php More information about regular expression can be found here: http://www.regular-expressions.info

How to add a google map in Contact us page of OpenCart? – no coding needed

This OpenCart tutorial shows you how to add a google map to the contact us page of OpenCart without coding or programming knowledge, we will show you how to use the HTML content default OpenCart module and add the map to the contact us page.

Let’s get started by going to https://google.com/maps then searching your locations in it. Once you find the location

Find the location in google map

When you click the “Share” icon you will see a popup click “Embed a map” then click “Copy HTML”

Google map embed code

Now go to your store OpenCart admin >> Extensions >> Extensions >> Choose the extension type “Modules” >> Then scroll to see the “HTML Content”. If you see the green button here, first click to install it.

Add HTML content module for google map

Then, click the blue button to add a new module.

Google map embed code
  • Enter the module name in “Module Name” field
  • Enter the title that you want to show in the front-end, you can leave it blank if you don’t need
  • Click the “Source Code” icon
  • Paste the google map HTML code
  • If you want full-width map then you have to change the width to 100%
  • Again click the Source code icon
  • Then click Save button

Now go to Admin >> Design >> Layouts >> Edit “Contact” then add the Google Map module in your desired position.

Then click save and see your front end.

You can see our demo here:

See Demo of Google map in Contact us page of OpenCart

Let us know if need any help

Opencart 3 theme free, download and documentation

We just started to create OpenCart 3 themes for free and keep on adding our modules which are also free. This post has OpenCart 3 theme for free, download and documentation is added to customize template CSS, and video tutorial so that you can install the OpenCart 3 theme easily.

Opencart 3 theme for free

How to install the OpenCart 3 theme?

  • Click to Download NepalBuddha theme
  • Extract it, enter into the folder “webocreation-master” and upload the folders to the respective folder, you can see the theme folder at catalog/view/theme which is named as “NepalBuddhaOpencartThemeFree
  • Go to admin >> Extensions >> Choose “Themes” in extension types and then edit the store
opencart theme free
  • Then, in “Theme Directory” choose “NepalBuddhaOpencartThemeFree”
opencart theme free directory selection
  • Click save and you will see the success message.
  • Go to the frontend and you will see the changes.

Let’s see a demo at the following URL:

See Demo of OpenCart 3 free theme

Following modules are directly integrated into the theme above:

You can change your template CSS at catalog>>view>>theme>>NepalBuddhaOpencartThemeFree>> stylesheet >> webocreation-style.css

You can see updates at Github:

Following are the setup documentation for the theme:

Please provide us with your ideas and requirement and we try to integrate into the theme as much as possible and make it free to use.

Install, configure, uninstall, remove OpenCart module video tutorial guide

In this opencart tutorial, we will show how to upload, install, configure, uninstall, delete and remove opencart 3 modules or extensions with which it became base for programmers to start making a custom module or theme.

Uploading a module in OpenCart

OpenCart is a module-based system that allows us to extend functionalities with an unlimited module instance system. What unlimited module instance system means is we can show many modules of one module on the same page and on many different pages. Let’s take an example of Banner module, we can show multiple banners in multiple places of one page and in other pages also.

To upload a module I will show you two ways, one through FTP and another through Admin panel which also needs FTP enabled. I am using OpenCart 3.0.2.0, a similar way for 2.2.

[slideshare id=126787901&doc=7-installingopencartmodule2-181226215806]

First, let’s install through FTP

Another way is through the Admin Panel:

Login into store administration panel and go to Extensions >> Extension installer.

module-installer

Now click on the upload button, a popup will show where you select zip file which ends with *.ocmod.zip or XML file which ends with *.ocmod.xml. Then click Ok. If you got a success message then files are uploaded properly.

module-upload-success

Now go to Extension >> Modifications, then click the clear button near the refresh button and check the Log tab.

If you see any errors then you have to solve them before clicking refresh. Some error may be like below:

2016-09-09 3:05:26 - MOD: Modification Default
FILE: system/engine/action.php
REGEX: ~(require|include)(_once)?\(([^)]+)~
FILE: system/engine/loader.php
REGEX: ~(require|include)(_once)?\(([^)]+)~
FILE: system/library/config.php\
REGEX: ~(require|include)(_once)?\(([^)]+)~
FILE: system/library/language.php
REGEX: ~(require|include)(_once)?\(([^)]+)~
FILE: system/library/template/php.php
REGEX: ~(require|include)(_once)?\(([^)]+)~
FILE: system/library/template/tiwg.php
REGEX: ~(require|include)(_once)?\(([^)]+)~
MOD: Newsticker
FILE: admin/controller/common/column_left.php
CODE: if ($this->user->hasPermission('access', 'design/layout')) {
FILE: admin/language/en-gb/common/column_left.php
CODE: $_['text_affiliate']
CODE: if ($this->user->hasPermission('access', 'design/layout')) {
NOT FOUND - OPERATIONS ABORTED!
----------------------------------------------------------------

If you don’t see any error then click refresh.

refresh-button

Whenever you enable/disable or delete a modification you need to click the refresh button to rebuild your modification cache!

If you click refresh and see error then you have to delete folder inside system\storage\modification, don’t delete index.html, then check the log again and solve it before you click refresh. If errors keep on showing then better not to use the module or hire experts.

Another way is Uploading XML file at system/ folder

You can directly upload the XML file in the system/ folder as well. Some modules like https://webocreation.com/opencart-free-extension-to-add-full-width-position-in-layout 

Sometime you may get the following errors while uploading module:

FTP needs to be enabled in the settings:

Your FTP is not enabled at your store, see this post on how to enable FTP in Opencart.

Invalid file type! :

You uploaded incorrect files and folders. Check whether the file name or zip ends with .ocmod.zip or ocmod.xml

While uploading the module if any files get overridden then it will show like below:

fileoverriden

Be sure you did not overridden your core files.

Could not connect as yoursitename.com:21

It means that it is unable to connect to your FTP. Check your FTP username, password, and port.

For an OCMOD file to be uploaded the file, the file extension must be either *.ocmod.zip or ocmod.xml. I think this is done to prevent uploading non OCMOD files from the store admin.

The file structure of OCMOD compressed zip ocmod.zip files may look like below but can differ as per the functionalities of the module:

ocmod_file_structure
  • Upload folder (All files under this directory will be uploaded to the directory of your OpenCart installation)
  • SQL (Database queries to add any create, drop, insert and update queries)
  • PHP (If the modification requires any custom PHP code then it needs to be placed here)
  • XML (The XML modification files which have a similar structure to VQMOD but have some changes)

Another file that we can upload is XML file then make sure it ends with NAME.ocmod.xml.

After installing the module and following the above steps, if you did not see any changes then you need to check the error logs of Ocmod at system/storage/logs

The modification requires a unique ID code!:

It means you have to open your .ocmod.xml file and change the text to unique text which is inside <code></code>

module-installer

The final step of the installation process is to apply the changes we have just made. In order to do so, go to Extensions -> Modifications and click the Refresh sign at the upper right corner of the page.

Installing a module:

Installing a module in OpenCart 2.x using the Extension installer is easy and intuitive. Go to Administration >> Extensions >> Modules in below OpenCart 2.3 but in above OpenCart 2.3 go to Administration >> Extensions then in the dropdown filter of “Choose the extension type”, select “Module”, you will see list of modules.

modue-filteration

Now you can install the module by clicking, Green + sign to install, red – sign to uninstall and red delete sign to delete, blue +  sign to add another instance of the module and blue pencil sign to edit the module.

module-install-uninstall

Uninstalling a module

Uninstalling is the easiest task that I have ever done. Go to Extensions >> Choose Modules, find the module that you want to uninstall in the Modules list and click on the uninstall red minus button. Then go to Extensions >> Modifications, click on the Uninstall button of the module that you want to uninstall and click Refresh sign. You are set and your module gets uninstalled.

Remove a module

First, uninstall the module then you have to delete every file that you upload when you install the module to remove a module.

Admin Controller file to make hello world module – OpenCart Module Development

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. Let’s start to create our hello world module by creating the file at the admin/controller/extension/module and named it helloworld.php. Then follow the following steps:

Create a class named ControllerExtensionModuleHelloWorld

Every module name should start with ControllerExtensionModule in OpenCart.
Use camel case style, avoid using special characters, URL path will be “extension/module/modulename” in our HelloWorld case it will be “extension/module/helloworld”.

Extends it with base class Controller

class ControllerExtensionModuleHelloWorld extends Controller {}

Create a public function named index

public function index(){}

This will load every time when we open the helloworld module
Opencart provides a Response class a simple PHP representation of an HTTP response message. This allows your applications to use an object-oriented interface to construct the response that needs to be returned to the client.

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

This loads the view helloworld.tpl from admin\view\template\extension\module\helloworld.tpl pass data from controller to view.

How to pass header, footer and column left section for helloworld module?

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

How to pass language data to view section?

The controller file is the place where we can load the language files to convert text into variables to be utilized in the template file. We can load the language file as below:

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

It means that the language file named helloworld.php is at admin/language/ACTIVE_LANGUAGE_FOLDER/extension/module

Then setup into the data variable as:

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

Now if you see the echo the heading_title at view file admin\view\template\extension\module\helloworld.tpl then you will see the output as following images.

Admin Controller file to make hello world module – OpenCart Module Development

  • In the view section:
    //adding breadcrumbs
    $data['breadcrumbs'] = array();
    $data['breadcrumbs'][] = array(
    'text' => $this->language->get('text_home'),
    'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true)
    );
    $data['breadcrumbs'][] = array(
    'text' => $this->language->get('text_extension'),
    'href' => $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=module', true)
    );
    $data['breadcrumbs'][] = array(
    'text' => $this->language->get('heading_title'),
    'href' => $this->url->link('extension/module/helloworld', 'token=' . $this->session->data['token'], true)
    );
  • In the view section:
    <ul class="breadcrumb">
    <?php foreach ($breadcrumbs as $breadcrumb) { ?>
    <li><a href="<?php echo $breadcrumb['href']; ?>"><?php echo $breadcrumb['text']; ?></a></li>
    <?php } ?>
    </ul>

How to add save and cancel button?

  • In the controller:
    if (!isset($this->request->get['module_id'])) {
    $data['action'] = $this->url->link('extension/module/helloworld', 'token=' . $this->session->data['token'], true);
    } else {
    $data['action'] = $this->url->link('extension/module/helloworld', 'token=' . $this->session->data['token'] . '&module_id=' . $this->request->get['module_id'], true);
    }
    
    $data['cancel'] = $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=module', true);
  • In the view section:
    <div class="pull-right">
        <button type="submit" form="form-html" data-toggle="tooltip" title="<?php echo $button_save; ?>" class="btn btn-primary"><i class="fa fa-save"></i></button>
        <a href="<?php echo $cancel; ?>" data-toggle="tooltip" title="<?php echo $button_cancel; ?>" class="btn btn-default"><i class="fa fa-reply"></i></a>
    </div>
    

Setting up the data variable value to pass to the view section:

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

Get the Submitted value of form in the controller:

  • Check whether the form is submitted or not $this->request->server[‘REQUEST_METHOD’] == ‘POST’
  • Get the submitted value of form in the controller: $this->request->post[‘name’]
  • Get the URL value:
    $this->request->get['module_id']

Get the modules values:

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

Validating the input type:

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;
    }

Permission Management

  • In the controller section:
    In the index function
if (isset($this->error['warning'])) {
    $data['error_warning'] = $this->error['warning'];
} else {
    $data['error_warning'] = '';
}

In the validate function

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

In the view section:

<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
    <button type="button" class="close" data-dismiss="alert">&times;</button>
</div>

The full code is below:

<?php

/**
 * Created by PhpStorm.
 * User: rnepali
 * Date: 10/1/2016
 * Time: 6:20 PM
 */
class ControllerExtensionModuleHelloWorld extends Controller {

    public function index(){
        //load the language file
        $this->load->language('extension/module/helloworld');
        //pass language file data to view
        $data['heading_title'] = $this->language->get('heading_title');
        $data['text_edit'] = $this->language->get('text_edit');
        $data['text_enabled'] = $this->language->get('text_enabled');
        $data['text_disabled'] = $this->language->get('text_disabled');
        $data['entry_name'] = $this->language->get('entry_name');
        $data['entry_title'] = $this->language->get('entry_title');
        $data['entry_status'] = $this->language->get('entry_status');
        $data['button_save'] = $this->language->get('button_save');
        $data['button_cancel'] = $this->language->get('button_cancel');

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

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

        $this->load->model('extension/module');
        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {

            if (!isset($this->request->get['module_id'])) {
                $this->model_extension_module->addModule('helloworld', $this->request->post);
            } else {
                $this->model_extension_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('extension/extension', 'token=' . $this->session->data['token'] . '&type=module', true));
        }


        //adding breadcrumbs
        $data['breadcrumbs'] = array();
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true)
        );
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_extension'),
            'href' => $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=module', true)
        );
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('extension/module/helloworld', 'token=' . $this->session->data['token'], true)
        );
        
        if (isset($this->request->get['module_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
            $module_info = $this->model_extension_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'] = '';
        }

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

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

        $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));
    }

    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;
    }

}
thanking_you

Fatal error: Cannot redeclare Loader::__get() in system\storage\modification\system\engine\loader.php

Fatal error: Cannot redeclare Loader::__get() in system\storage\modification\system\engine\loader.php

Go to YOUR_INSTALLED_FOLDER/system\storage\modification then delete all files and folder except index.html

Then refresh the front end, hope it works.

Then again install your ocmod.xml again.

The directory containing files to be uploaded could not be found: OpenCart error

If you have come up with OpenCart error “Directory containing files to be uploaded could not be found” then it means you are uploading extensions. It means you are missing upload/ folder. Extract the files and create the upload/ folder then zip it again and upload that folder.

Following are the OCMOD file and folder structure

ocmod-file-and-folder-structure

Hope it helps to solve your issues. You can see OpenCart error: Modification requires a unique ID code!