Home Blog Page 22

News Ticker Opencart Module for free Opencart 2

Opencart News Ticker is the module for Opencart version 2 which shows lines as the ticker and we have made this as the module so we can show wherever module can be shown. Click for Newsticker OpenCart 3 version

DOWNLOAD:

INSTALLATION:

If your FTP is enabled from the admin section:

  1. Upload the NewsTicker.ocmod.zip from Extensions >> Extension Installer
  2. All will be set.

If FTP is not set then follow the following steps:

  1. Download the module
  2. Extract the zip file or Unzip the downloaded file.
  3. Upload the catalog and admin folder which is inside “NewsTicker.ocmod/upload” folder to your server respective folder
  4. Upload the files inside the “upload” folder to your OpenCart root folder.
  5. Now login to admin section then go to Extensions >> Extension Installer >> where you upload the newsticker.ocmod.xml
  6. After successful installation, go to Extensions>> Modification and click the log tab and see if some errors are showing, if the error shows then you have to solve it first.
  7. If no error click the refresh button
  8. You are all set.
  9. Enjoy the free module.

If you see the module listed then you are set, now install the module.

Newsticker module listing

Another with the installation of newsticker.ocmod.xml you will see “NewsTicker” on the left menu.

newsticker module at left menu

If you see these two things then you have installed your files and folder properly.  Now time to configure the module.

First, we install the module, install the database, then insert data of newsticker, then add the module and insert data to the module and configure at layouts to show an information page.

Install the NewsTicker Module:

Go to Extensions >> Extensions >> Choose Modules in Extension Type >> In NewsTicker Module click Install button. Then click the edit button.

DATABASE INSTALLATION:

database table missing

At the start of the module edit, you will see the following instruction to install the Database.

It will run the following query at your database:

<?php 
    class ModelNewstickerInstall extends Model {
        public function addExtensionTables() {
            $this->db->query("CREATE TABLE IF NOT EXISTS ". DB_PREFIX . "newsticker(
            `newsticker_id` int(11) NOT NULL,
            `name` varchar(64) NOT NULL,
            `status` tinyint(1) NOT NULL,
            PRIMARY KEY (`newsticker_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1");

            $this->db->query("CREATE TABLE " . DB_PREFIX . "newsticker_description(
            `newsticker_description_id` int(11) NOT NULL,
              `newsticker_id` int(11) NOT NULL,
              `language_id` int(11) NOT NULL,
              `name` varchar(255) NOT NULL,
              `message` varchar(255) NOT NULL,
              `position` int(3) NOT NULL DEFAULT '0',
              PRIMARY KEY (`newsticker_description_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1");

            $this->db->query("ALTER TABLE " . DB_PREFIX . "newsticker
            MODIFY `newsticker_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1");
            $this->db->query("ALTER TABLE " . DB_PREFIX . "newsticker_description
            MODIFY `newsticker_description_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1");

        }
    }
?>

When you clicked the Install Database then your database table is installed.

Now when you go to Extensions >> Extensions >> Choose Modules in Extension Type >> In NewsTicker Module click Edit button. Then you will see like below:

newsticker list instruction

Click on the “here”. It will take you to place to insert the newsticker. We made like this so that we can add many news-tickers to different places as needed.

adding newsticker list

Now click on the add button.

inserting newsticker list

By filling the above form click save.

Configuration of the NewsTicker Module:

Now again go to Extensions >> Extensions >> Choose Modules in Extension Type >> In NewsTicker Module click Edit button

newsticker module configuration

Configuring layout of NewsTicker to show at Information Page:

Go to Design >> Layouts >> Edit Information from the list >>

layout section newsticker module

Click the add button at the Content Top layout, then choose “Information Page News Ticker” from the dropdown. Then click Save.

Front end or Presentation section to see the NewsTicker Module. Go to About us page of Information pages. Then you will see as follows:

newsticker opencart module free

You are set to show NewsTicker at the information page. Likewise, you can show different layout and position on different pages.

FEATURES:

  • Displays news ticker on any page and position.
  • All features that modules need to have.
  • Sentences or news can be inserted from the admin section.
  • Compatible with all major browsers (Firefox, IE8, Safari, Chrome, and Opera).
  • Tested with the Opencart version 2.3.0.1 only with the default theme.
  • Easy installation I think.
  • OCMOD / vQmod support

DEMO:

https://webocreation.com/nepalbuddha/

HOW TO INSERT THE NEWS or SENTENCE

Go to Admin >> Design >> NewsTicker and you can insert or edit the existing one. Click plus button to insert the new line you want to show at the NewsTicker module.

Permission Denied!

You do not have permission to access this page, please refer to your system administrator.

Go to the System >> Users >> User Groups and edit the Top Administrator and then check as in the figure:

permission for news ticker module of opencart
permission for news ticker module of opencart

It means we have to give permission to the catalog/newsticker.

Code of OcMod of NewsTicker Module:

<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>Newsticker</name>
    <version>1.0</version>
    <author>WebOCreation</author>
    <link>https://webocreation.com</link>
    <code>webocreation_newsticker_1_1</code>
    <file path="admin/controller/common/column_left.php">
        <operation>
            <search><![CDATA[
            if ($this->user->hasPermission('access', 'design/layout')) {
            ]]></search>
            <add position="before"><![CDATA[
            if ($this->user->hasPermission('access', 'design/newsticker')) {
				$design[] = array(
					'name'	   => $this->language->get('text_newsticker'),
					'href'     => $this->url->link('design/newsticker', 'token=' . $this->session->data['token'], true),
					'children' => array()
				);
			}
            ]]></add>
        </operation>
    </file>
    <file path="admin/language/*/common/column_left.php">
        <operation>
            <search><![CDATA[
            $_['text_affiliate']
            ]]></search>
            <add position="before"><![CDATA[
            $_['text_newsticker']='NewsTicker';
            ]]></add>
        </operation>
    </file>
</modification>

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.

All jquery is used from the following contributor:
http://www.jquerynewsticker.com/

Enjoy!

For questions, errors, suggestions, and requests you can mail me at webocreation.com@gmail.com. You can follow at my twitter account @rupaknpl and subscribe to YouTube user OpencartTutorials.

Search terms:

scroll text module in opencart, show text at the top on opencart, jquery web ticker module for opencart, jquery marquee module in opencart, jquery scroller module for opencart,

OpenCart 3 Library Global objects Methods – OpenCart video training

Hey everyone! Rupak Nepali again. In our last video, we talked about “How to create database table?“, Today we are talking about “OpenCart Library Predefined Objects’ Methods”.

An object has functions associated with it that are known as the object’s methods. Here we show predefined objects that OpenCart provided for which you don’t need to create or initialize the objects, you can use it directly. So better to know them so that it helps in achieving DRY which means Don’t Repeat Yourself.

Don’t write code unless you should. Write code only what you need, if you missed these predefined objects’ methods then you may repeat codes.

Opencart has many predefined objects’ methods that can be called in Controller and Model.  Like in the admin section we can see predefined objects like config, log, event, load, request, response, DB, session, cache, URL, language, open-bay, document, customer, currency, tax, weight, length, cart, encryption, model_setting_event, the user.

Let see an example of a database object:
The database object of OpenCart is $this->db, which has the following methods. All SQL queries are run from $this->db->query method which looks like below. For Select, replace, delete, update we use it like this in OpenCart and this returns three properties:

  • Database Object of Opencart is
    $this->db
  • Methods are:
    $this->db->escape($value) – mysql_real_escape_string() on the value passed
    $this->db->countAffected() – rows affected by an UPDATE query
    $this->db->getLastId() – last auto increment id same as mysql_insert_id()
    $this->db->connected() – Pings a server connection, or tries to reconnect if the connection has gone down
  • $this->db->query($sql)
  • All SQL queries are run from $this->db->query method which looks like:

    $query = $this->db->query(“SELECT * FROM ” . DB_PREFIX . “category WHERE
    $this->db->query(“REPLACE INTO `” . DB_PREFIX . category_path` SET …);
    $this->db->query(“INSERT INTO `” . DB_PREFIX . category_path` SET …);
    $this->db->query(“DELETE FROM ” . DB_PREFIX . “category WHERE …);
    $this->db->query(“UPDATE ” . DB_PREFIX . “category SET image = …);

  • $this->db->query method returns three properties:
    $result->num_rows = $query->num_rows; – gets the number of rows in a results
    $result->row = isset($data[0]) ? $data[0] : array(); – get the first row data
      $result->rows = $data; – get an array of row results

$this reference in the controller:

Go to admin/controller/extension/module account.php and var_dump the $this,

echo “<pre>”;
var_dump($this);
echo “</pre>”;
exit();

$this is a reference to the calling object, usually the object to which the method belongs. You can see the protected modifier registry which has config, log, event, load, request, response, etc.

Now let’s take config object:

echo “<pre>”;
$class_methods = get_class_methods($this->config);
print_r($class_methods);
echo “</pre>”;

Now you can see the list of method that you can use in your config object.

Let’s see the parameters that you can use in the get and set methods:
echo
“<pre>”;
var_dump($this->config);
echo “</pre>”;
exit();

Now let’s say we want the site URL then we can easily get it as:

print_r($this->config->get(‘site_url’));
exit();

In this way, you can keep on using other objects and methods that OpenCart provide.

Let’s take another example of the customer predefined object methods provided by OpenCart.

For that we can see at system/library/cart/customer.php:

You can see the namespace Cart which is like a directory, in OpenCart 3 Customer is now under “Cart” namespace. Customer object is instantiated as:

$customer = new Cart\Customer($this->registry);

So, in Customer class there are private properties and public methods login, logout, islogged, getId, getFirstName, getLastName, getGroupId, getEmail, getTelephone, getNewsletter, getAddressId, getBalance and getRewardPoints.

These public methods are available in the Controller and Model class of modules which I already showed for config object and it’s similar for other objects as well.

You can see the login method of customer object is used in catalog/controller/account/login.php,

You can see the $this->customer->login validate() method

 Like this, we use the predefined method wherever we need it.

This login method is used to provide the authentication for customer section of OpenCart. Customer session is activated for customer_id, first name, last name, customer_group_id, email, telephone, newsletter and address_id is assigned.

If you check the customer object without login all value assigned are null,

echo “<pre>”;
var_dump($this->customer);
echo “</pre>”;

 once you logged in values, you can see these values.

Now in code you can get those values through public methods provided by customer object to get the first name we have getFirstName method:

echo “<pre>”;
print_r($this->customer->getFirstName());
echo “</pre>”;

If you are confused of how to get the class methods name then PHP have get_class_method function:

echo “<pre>”;
$class_methods = get_class_methods($this->config);
print_r($class_methods);
echo “</pre>”;

With this logout method is used to unset the customer session and assign empty valued.

isLogged method of customer object is used to check whether customer_id is active or not

getId to get the customer_id

getFirstName method is used to return active customer first name

getLastName method is used to return active customer last name.

getEmail is used to return active customer email

getTelephone returns active customer telephone number.

Similarly, the customer object has the following other public methods:

getnewsletter

getAdddressId

getBalance

getRewardPoints

Some other predefined objects provided by OpenCart are the following:

Pre defined objects in Opencart

Cart, you can see the system/library/cart/cart.php where you can see the public methods that can be accessed from your modules. You can see here getProducts method, add method, remove method and so on.

Namespace in OpenCart

  • A namespace is like a directory and by adding ‘namespace’, Affiliate is now under ‘Cart’.
  • To use ‘Affiliate’, we call or instantiate as new Cart\Affiliate()
  • Adding a ‘namespace’ to a class is like organizing files from one directory into a bunch of sub-directories.
  • The use statement lets us call class by a nickname.

Affiliate

  • $this->affiliate->login($email, $password);
    You can find code used at catalog/controller/affiliate/login.php validate() method.
    Affiliate login script at system/library/cart/affiliate.php is used to provide the authentication for the Affiliate section of OpenCart. Affiliate session is activated for affiliate_id, firstname, lastname, email, telephone, fax, and code.
  • $this->affiliate->logout()
    You can find the code used at catalog/controller/affiliate/logout.php index() method.
    Affiliate logout script at system/library/cart/affiliate.php  is used to unset the affiliate session and assign empty value to affiliate_id, firstname, lastname, email, telephone, and fax of Affiliate. By this Affiliate is logged out.
  • $this->affiliate->isLogged()
    You can find the code used at catalog/controller/affiliate/account.php index() method.
    Affiliate isLogged script at system/library/cart/affiliate.php is used to check whether affiliate_id is active or not.
  • $this->affiliate->getId()
    You can find code used at catalog/model/affiliate/affiliate.php editAffiliate($data) method.
    Affiliate getId script at system/library/cart/affiliate.php  is used to return active affiliate_id.
  • $this->affiliate->getFirstName()
    You can find code used at catalog/controller/affiliate/login.php index() method.
    Affiliate getFirstName script at system/library/cart/affiliate.php is used to return active affiliate first name.
  • $this->affiliate->getLastName()
    You can find code used at catalog/controller/affiliate/login.php index() method.
    Affiliate getLastName script at system/library/cart/affiliate.php  is used to return active affiliate last name.
  • $this->affiliate->getEmail()
    You can find code used at catalog/controller/affiliate/edit.php validate() method.
    Affiliate getEmail script at system/library/cart/affiliate.php is used to return active affiliate email.
  • $this->affiliate->getTelephone()
    Not used in OpenCart but you can use it J.
    Affiliate getTelephone script at system/library/cart/affiliate.php  is used to return active affiliate Telephone number.
  • $this->affiliate->getCode()
    You can find code used at catalog/controller/affiliate/tracking.php index() method.
    Affiliate getCode script at system/library/cart/affiliate.php is used to return active affiliate tracking code which is used to track referrals.
  • $this->affiliate->getFax()
    Not used in OpenCart but you can use it J.
    Affiliate getFax script at system/library/cart/affiliate.php  is used to return the active affiliate Fax number.

Other Global Methods

  • Cart
  • Currency
  • Customer
  • Length
  • Tax
  • User
  • Weight
  • Config
  • DB
  • Document
  • Encryption
  • Image
  • Language
  • Log
  • Mail
  • Openbay
  • Pagination
  • Request
  • Response
  • Session
  • Template
  • URL

For Detail, the description read “OpenCart Theme and Module Development” book

OpenCart theme and module development

https://www.packtpub.com/web-development/opencart-theming

So, you get where to see the OpenCart library predefined objects’ methods which we can use in our Model and controller classes. Keep digging.

So, for a detailed description of predefined methods of OpenCart read the “OpenCart Theme and module development” book.

Like this, we completed our fifth video “OpenCart library Predefined Objects’ Methods”, in our next video we will show “OpenCart Code flow. Request and response in OpenCart”. Keep on tuning.

As always please don’t forget to post your questions or comments so that I can add extra topics or things that I need to develop which will help to develop the quality of videos series. You can follow at my twitter account @rupaknpl and subscribe to our youtube channel Opencart tutorials. Similarly, keep on visiting my personal blog where you will find lots of free modules.

See you in the next video and happy learning and thanks for watching videos.

Exploring the code of default Featured Module

To explore the code of defualt featured module, let’s start with listing what files are used by the Featured module:

Admin folder files:

Catalog folder files:

How to know which files are used by module?

Always look to the URL. For Featured module, go to Admin >> Extensions >> Extensions >> Choose “Modules” from the dropdown. Then find the “Featured” and then click the blue Add button (if the module is already installed nor you have to install the module and click the blue button). You will see URL like below:

http://localhost/opencart2302/admin/index.php?route=extension/module/featured&token=LMEWZBoKMxfr1D7s2dhYe5niRfOAz0Ak

See the value of route, here route=extension/module/featured, as this is in admin so your token value may be different.

While seeing for the files always start from the route, the route gives you the controller file and inside the controller, we can find the language file, model file, and template file.

Now as per the route value go to admin folder >> controller folder >> extension folder >> module folder >> and find featured.php file.

In this way, you can find the controller file, controller file end with .php extension. From controller file you can find the language file used by that controller with lines of code as

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

It means that admin >> language >> LANGUAGE folder >> extension folder >> module folder  >> featured.php

Like that you can find the language file, language file ends with .php extension.

To find the view file find code that start with $this->response->setOutput. In the featured module it is like below:

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

It means that admin >> view >> extension folder >> module folder >> featured.tpl

Like this way you can find the view file, view files end with .tpl extension.

Things to consider while creating database Model Data OpenCart Guide

Hi everyone, Namaste, Me Rupak Nepali. In our third video, we describe OpenCart files and folders and told you that the next video will be of OpenCart code flow but while making the PowerPoint we feel like first, we need to know about the database and global methods of OpenCart then it will be easier to understand the OpenCart code flow. So, in this video, we will go through the OpenCart database.

Things to consider while creating database OpenCart Guide

  • OpenCart supports multistore
  • It supports multi-language
  • Multiple Layouts
  • oc_ is a database prefix
  • If you are creating the table then better to make 4 tables, one which will contain language-specific contents here oc_information_description, another is non-language specific oc_information and another which joins with the store, and the last one which joins to the layout.
database schema creation OpenCart

Create custom table schema in OpenCart:

If you are going to create a custom table in OpenCart then you have to think of four tables. One table contains non-language-specific data like in the above image oc_information, another table is language-specific in the above image oc_information_description, another table shows the relationship between store and data in the above image oc_information_to_store and the last one which shows the relationship between layout and data.

So if I want to create a custom table that contains testimonials then my table schema will be like in the image:

custom table schema for Testimonial

Code example:

  • Create a model file:
    admin>>model>>catalog>>information.php
  • Create a class as per the folder and file structure:
    class ModelCatalogInformation extends Model
  • Create a Method inside the class:public function addInformation($data)
  • In Controller, first, load the model then call the method:
    $this->load->model(‘catalog/information’);
    $this->model_catalog_information->addInformation($this->request->post);

Download the full Opencart Database Schema by clicking the PDF below:

How to show relationships and only some databases in PHPmyadmin?

PHPmyadmin Tables relationship

So, by making the database table we completed our fourth video, we hope you liked it. As always please don’t forget to post your questions or comments so that I can add extra topics or things that I need to develop which will help to create the quality of the video series. You can follow me at my Twitter account @rupaknpl and subscribe to our youtube channel Opencart Tutorials. Similarly, keep on visiting my personal blog https://webocreation.com where you will find lots of free modules.

The next video will see “OpenCart Library Global Objects’ Methods“. So, see you in the following video, and happy learning, and thanks for watching the videos.

Describing files and folder of OpenCart Framework

File and folder structure of Opencart

Describing files and folders and OpenCart Framework
Hi everyone, Namaste. Namaste is the word used in our Country Nepal to greet someone. Me Rupak Nepali. In our second video, we install OpenCart, and is now up and running at our custom URL “webocreation.loc”. Today in our third video we are going to describe files and folders of the OpenCart framework.

The first thing we do is look through the files and folders structure.

Admin section files and folders are in the admin/ folder. It has controller/ language/ model/ and view/ folder, if you are developing for admin sections then these are the folders you are going to touch.

catalog/ folder holds all frontend presentation style files and folders.

We will discuss in detail these folders when we will start making the hello world module.

The image/ folder contains cache/, catalog/ and payment/ folder with no_image.png and placeholder.png files. Placeholders and no images are used if there are no images found. For example, let’s go to the category page.

You see this is the placeholder image.

no image placeholder Opencart

The catalog/ folder inside the image/ folder contains the main images that we upload either from the backend or frontend. Like category images, product images, images inserted from the text area, etc.

The cache/ folder inside the image/ folder contains resized images of the main images. For example, in the demo/ demo folder, we have iPhone6.jpg which is the main image. But while showing in the category page or on the product page its size is resized. All these images are stored in the cache folder. We can see at cache/ folder demo, then banners see the name iPhone6-1140*380.jpg which is resized the image for the banner at the home page.

In this way, images are handled in the image/ folder.

Install/ folder contains an opencart.sql file which creates tables on the specified database and inserts demo data. Other files have codes that facilitate to installation OpenCart.

The system/ folder is the base where the OpenCart framework is defined. It contains config/, engine/, helper/, library/ and storage/ folders. We will provide details of these folders in the next video with the code flow.

.htaccess.txt is a configuration file used on web servers running the Apache Web Server software where you rename the htaccess.txt to .htaccess. Mostly we use this for the SEO URL redirects in OpenCart

Other is the config.php file where constant is defined and is different as per installation.

index.php where we can find what version of OpenCart are we using and the start of our application.

The last one is the php.ini file, which is the configuration file for running applications. It is used to control variables, magic_quotes_gpc, register_globals, default_charset, memory_limit, max_execution_time, and many other. Shared hosting does not provide these facilities to change it but if you are hosting in Private servers then you can set to use them.

The following image shows how our files of the module are placed in OpenCart:

Files and folders of hello world module

So, our third video is completed, hope you liked it. As always please don’t forget to post your questions or comments so that I can add extra topics or things that I need to develop which will help me to develop the quality of the videos series. You can follow me at my Twitter account @rupaknpl and subscribe to our youtube channel Opencart tutorials. Similarly, keep on visiting my personal blog https://webocreation.com where you will find lots of free modules.

In the next video, we will show you the OpenCart Framework code flow. So, don’t miss it as if you understand this flow then you can start coding without seeing other videos. So, see you in the next video, and happy learning, and thanks for watching and liking my videos.

Installing the OpenCart and creating the custom URL virtual host Xampp: OpenCart Module Development Video Tutorial

Hi everyone! Me Rupak Nepali. I am very excited about the first video success – “Introduction and Table of Contents – OpenCart Development” and now this is the second video. In which I will install OpenCart 3.0.2.0 locally and set up a custom URL to work locally.

To begin the installation process, first, download OpenCart. Let’s go to OpenCart.com and download it. Now let’s go to D: /xampp/htdocs folder as I have installed Xampp at D: / folder.

Now create a folder, we are going to create webocreation/ folder where we extract the zip folder we downloaded. Then go to upload/ folder and copy all files and folder and paste to the webocreation/ folder.

Now let’s create a database. Go to localhost/phpmyadmin, create a database named “webocreation”.

Now first let’s create custom URL to work locally:

Steps to create custom URL to work locally:

  • Open up the Xampp control panel and stop Apache (Ensure that you don’t have it running as a service.
  • Navigate to D:/xampp/apache/conf/extra or wherever you installed Xampp
  • Open up your text editor with administrative privileges and open up httpd-vhosts.conf found in the D:/xampp/apache/conf/extra folder
  • At the very bottom of the file paste the following (check if it exists there already)
NameVirtualHost *:80
<VirtualHost *:80>
DocumentRoot "D: /xampp/htdocs"
ServerName localhost
</VirtualHost>
  • Without that line of code, you will lose access to your default htdocs/ For eg: http://localhost/ will be inaccessible.
  • Now write the virtual host code here for our webocreation folder:
<VirtualHost *:80>
DocumentRoot "D: /xampp/htdocs/webocreation"
ServerName webocreation.dev
ServerAlias www.webocreation.dev
<Directory "D: /xampp/htdocs/webocreation">
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
  • Now we head over to our Windows Hosts File, to edit the HOSTS. The file will be located at C: /Windows/System32/drivers/etc/hosts, where hosts are the file.
127.0.0.1             localhost
  • look for the line above, and enter your site mimicking the layout
127.0.0.1             localhost
127.0.0.1             webocreation.dev
  • Change this to the domain name you choose earlier
  • Change it to reflect the lines above (if you have problems saving it meant you didn’t have your text editor running in admin mode.
  • Restart Apache and test to make sure it is working.

Now go to the URL webocreation.dev. Here we go our custom URL is activated, now we are installing OpenCart.

Let’s agree with the License Agreement by clicking the continue button. If you see any red highlights then we are having some issues. See here our config.php file is missing. Similarly, you may see other errors then you have to solve them. One could curl disabled which you have to enable from php.ini

In ours let’s create the config.php file at root/ folder and admin/ folder. Reload it. Once all issues are solved then click the continue button. The next screen prompts you for information about the database you’ll be using and asks for the database username and password field. We already created “webocreation” database, with a root username and a blank password.

Now let’s enter username and password for the administration. I am creating a very hard password which I recommend not to use in your installation. All this is because of laziness and I don’t need the installation to be secure; accepting the easiness, in this case, is fine. In a production OpenCart installation, be sure that you have a unique username and password for both the administrator and the database for security reasons.

Provide your email mine is webocreation.com@gmail.com, then click continue button.

Your installation is complete.

Now don’t forget to delete the install folder, I see in most clients programmer just rename the install/ folder and by-passing error message but there will be security holes remained in that folder so the hacker can find it easily and exploit your database so strongly recommended to delete the install/ folder after installation is complete.

Now you can view the front end, login to the administration section and insert categories, product and set up shipping and payment gateway and your online store is ready to take the order.

So I am at the end of the second video, I hope you liked it. Please, please don’t forget to post your questions or comments so that I can add extra topics or things that I need to develop which will help me to develop the quality of videos series. You can follow at my twitter account @rupaknpl and subscribe to our youtube channel “onlinegyannepal”. Similarly, visit my personal blog https://webocreation.com.

In the next video, I will be describing files and folder and OpenCart Framework. So, see you in the next video and happy learning and thanks for bearing me for 8 mins.

Configure and show how default featured module works Opencart 3

To configure and show default featured module you need to login to the Admin dashboard, then follow the following steps:

  1. Admin >> Extensions (Left Menu) >> Extensions >> Choose ‘Modules’ from the select box.
  2. It will list modules
  3. Find the Featured Module
  4. Then check ff the Featured module is already installed or not, if not installed then click on the green install button, or you can start by clicking on the blue edit button in order to
    configure the featured product.
  5. On clicking the blue edit button of the Featured product, you will see as the following image:
  6. Enter the Module Name.
  7. Now, start typing the name of the product in the Products field. It is autocompleted and pops up a list of the names of products that match with the words of the typed product name.
  8. Select the products you want to display in the featured products.
  9. Now, to add another product, just start typing again and choose the right product.
  10. Like this, you can make a list of featured products.
  11. If you don’t want a product on the featured list, then click on the black minus sign to the left of the product, and the product will be removed from the list.
  12. Limit: Number of products to show in front.
  13. Width: Width for the product’s image.
  14. Height: Height for the product’s image.
  15. Status: Shows at the frontend only if it is enabled.
  16. Now click the blue Save button at the top right.
  17. By the above steps, we install and configure the Featured module. Now to show at the front we have to work out on the layout.
  18. Let’s say we want to show the module in Information pages.
  19. For that go to the Admin >> Design >> Layout
  20. From the list of the layout edit the Information
  21. Then in the Content Top section click the plus blue button and select the Information Page Featured Module.
  22. Then click save button
  23. Now go to the front page and go to about us page, you will see like as in the below image

Like this way, you can install, configure and show the featured module at the presentation layer.

Enjoy!

For questions, errors, suggestions, and request you can mail me at webocreation.com@gmail.com. You can follow at my twitter account @rupaknpl and subscribe to YouTube user OpencartTutorial.

OpenCart error : Modification requires a unique ID code!

While installing the OpenCart module if you found OpenCart error: Modification requires a unique ID code! then it means that either you are missing <code>ModuleUniqueName</code> or there is a conflict with another module unique name.

If you are missing <code> code

If you are missing <code> means, while writing ocmod.xml file you missed to write <code>ModuleUniqueName</code> which we missed most.

Open your “*.ocmod.xml” file of your module you are installing then add following lines inside modification schema:

<code>Module Unique Name</code>

Like in our list all opencart module all.install.ocmod.xml contains <code>List_all_Products</code>:

<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>List Out All Products OpenCart 2.3 OCmod</name>
    <version>1.0</version>
    <author>Rupak Nepali, Webocreation.com</author>
    <code>List_all_Products</code>
    <link>https://webocreation.com</link>
    <file path="catalog/view/theme/*/template/common/header.tpl">
        <operation>
            <search><![CDATA[
            <ul class="nav navbar-nav">
            ]]></search>
            <add position="After"><![CDATA[
            <li><a href="index.php?route=product/allproduct">All Products</a></li>
            ]]></add>
        </operation>
    </file>
</modification>

If there conflict with another module unique name

Then rename the name within <code>ModuleUniqueName</code> and install it again you will see following:

openart successfull installation of ocmod module

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

Happy successful module installation, you can let me know if you found any issues then we can solve. If you like to read more about the Ocmod then read OCMOD Modification System opencart 2.3

Fatal error: Cannot use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\Bool as Bool because ‘Bool’ is a special class

Fatal error: Cannot use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\Bool as Bool because ‘Bool’ is a special class

When you update your PHP version and you can see the above issue while working in the Expression Engine. I just commented out the following at core\EllisLab\ExpressionEngine\Library\Parser\Conditional\Lexer.php the boolean and string annotations:

use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\Token;
//use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\Bool;
use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\Comment;
use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\Number;
use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\Operator;
use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\Other;
//use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\String;
use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\Tag;
use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\Variable;

and following on the same file the bool part and the string part

switch ($type)
{
    //case 'BOOL':	 $obj = new Bool($lexeme);
    //	break;
    case 'COMMENT':	 $obj = new Comment($lexeme);
        break;
    case 'NUMBER':	 $obj = new Number($lexeme);
        break;
    case 'OPERATOR': $obj = new Operator($lexeme);
        break;
    case 'OTHER':	 $obj = new Other($lexeme);
        break;
    //case 'STRING':	 $obj = new String($lexeme);
    //	break;
    case 'TAG':		 $obj = new Tag($lexeme);
        break;
    case 'VARIABLE': $obj = new Variable($lexeme);
        break;
    default:
        $obj = new Token($type, $lexeme);
}

I disable the string part also because I get the following issues as well:
Fatal error: Cannot use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\String as String because ‘String’ is a special class name

Then I commented out following \core\EllisLab\ExpressionEngine\Library\Parser\Conditional\Parser.php

//use EllisLab\ExpressionEngine\Library\Parser\Conditional\Token\Bool;

With these two file changes above error is removed but I have not gone too deep issues inside it, make changes in your own risk 🙂

Drupal error white user page, the design is showing in the index page, database contents are not showing in eCommerce website

While working with one of the eCommerce websites I came up with a drupal error that shows a blank white page when I try to go to admin or /user but design and CSS are showing, only database contents are not showing.

I searched many things but not able to find a solution and solve them simply by clearing caches. I thought to clear the cache but I am not able to log in and not able to go to link /admin/config/development/performance.

Thus I found following code to flush all caches. I kept following code in \sites\all\themes\theme_name\templates\page.tpl.php and hard refresh by performing crtl+F5

<?php
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  drupal_flush_all_caches();
?>

Then, boooom my pages are back with contents, now started working normally 🙂

Thanks for the drupal_flush_all_caches method 🙂

Fatal error: Uncaught Error: Call to undefined function _system_default_theme_features() in D:\xampp7\htdocs\..\includes\theme.inc on line 1430( ! ) Error: Call to undefined function _system_default_theme_features() in D:\xampp7\htdocs\..\includes\theme.inc on line 1430Call Stack#TimeMemoryFunctionLocation10.08306089760_drupal_exception_handler( )…\bootstrap.inc:020.08306090232_drupal_log_error( )…\bootstrap.inc:236530.08306091904theme( )…\errors.inc:24540.08606224864template_preprocess_maintenance_page( )…\theme.inc:112550.08606224896theme_get_setting( )…\theme.inc:2796

Add following line to D:\xampp\apache\conf\httpd.conf if your website keeps on showing “Connection Errors”

<IfModule mpm_winnt_module>
   ThreadStackSize 8388608
</IfModule>

Error encountered after disabling the cache in Drupal

Following is the error encounter after disabling the cache in Drupal
The website encountered an unexpected error. Please try again later.
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service “cache.backend.null”. Did you mean one of these: “cache.backend.apcu”, “cache.backend.php”, “cache.backend.memory”? in Drupal\Component\DependencyInjection\Container->get() (line 161 of core\lib\Drupal\Component\DependencyInjection\Container.php).

Drupal\Component\DependencyInjection\Container->get('cache.backend.null')
Drupal\Core\Cache\CacheFactory->get('render')
call_user_func_array(Array, Array)
Drupal\Component\DependencyInjection\Container->createService(Array, 'cache.render')
Drupal\Component\DependencyInjection\Container->get('cache.render', 1)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Object)
Drupal\Component\DependencyInjection\Container->createService(Array, 'http_middleware.page_cache')
Drupal\Component\DependencyInjection\Container->get('http_middleware.page_cache', 1)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Object)
Drupal\Component\DependencyInjection\Container->createService(Array, 'http_middleware.reverse_proxy')
Drupal\Component\DependencyInjection\Container->get('http_middleware.reverse_proxy', 1)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Object)
Drupal\Component\DependencyInjection\Container->createService(Array, 'http_middleware.negotiation')
Drupal\Component\DependencyInjection\Container->get('http_middleware.negotiation', 1)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Object)
Drupal\Component\DependencyInjection\Container->createService(Array, 'http_kernel')
Drupal\Component\DependencyInjection\Container->get('http_kernel')
Drupal\Core\DrupalKernel->getHttpKernel()
Drupal\Core\DrupalKernel->handle(Object)

Solution:

Run http://www.example.com/rebuild.php then reload and it works again. Researching why is this. Please let me know if found anything.

Drupal Console: [ERROR] Command “site:status”, is not a valid command name

Drupal Console: [ERROR] Command “site:status”, is not a valid command name.

First try/execute the drupal list command, where you will get a list of available command. If you don’t see the site:status then it means you have not installed the drupal, so Execute the drupal site:install command and again perform drupal list now hope you will see list of commands which you can perform site:status and other commands.

Front end Controller file to make hello world – OpenCart Module Development

OpenCart identifies existing modules automatically, simply by reading the catalog/controller/extension/module folder. Any modules existing in this folder will automatically be loaded as per the active modules for the pages on the front end.

Let’s start to create our hello world module by creating the file at 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 frontend also.
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”.

Code is written for Front end Controller file to make hello world – OpenCart Module Development

<?php
class ControllerExtensionModuleHelloWorld extends Controller {
    public function index($setting) {
        $data="";
        if (isset($setting['name'])) {
            $data['name'] = $setting['name'];
        }
        return $this->load->view('extension/module/helloworld', $data);
    }
}

In the above code for helloworld module which will show text at the front end,

  • Class name is ControllerExtensionModuleHelloWorld
  • This class extends the base Controller class
  • Have a public index function declaring $setting as arguments
  • This $setting holds all the values available for the module. For example when we do print_r for the $setting we find following: Array ( [name]=> This is hello world module text [status]=> 1 )

So we can assign to $data array to pass it to view section like:

if (isset($setting['name'])) {
      $data['name'] = $setting['name'];
}

Then return the loaded view as:

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

Now in the view section, catalog\view\theme\default\template\extension\module\helloworld.tpl, you can write the following code and show the output:

<div>
    <h2><?php echo $name; ?></h2>
</div>

Like this way you can show hello world text at the front end:

controller-helloworld-module-opencart

Service ‘page_manager.variant_route_filter’ for consumer ‘router.no_access_checks’ does not implement

Service ‘page_manager.variant_route_filter’ for consumer ‘router.no_access_checks’ does not implement

The website encountered an unexpected error. Please try again later.

Symfony\Component\DependencyInjection\Exception\LogicException: Service ‘page_manager.variant_route_filter’ for consumer ‘router.no_access_checks’ does not implement Drupal\Core\Routing\FilterInterface. in Drupal\Core\DependencyInjection\Compiler\TaggedHandlersPass->processServiceCollectorPass() (line 164 of D:\xampp\htdocs\axway\corporate-8\web\core\lib\Drupal\Core\DependencyInjection\Compiler\TaggedHandlersPass.php).
Drupal\Core\DependencyInjection\Compiler\TaggedHandlersPass->processServiceCollectorPass(Array, ‘router.no_access_checks’, Object) (Line: 97)
Drupal\Core\DependencyInjection\Compiler\TaggedHandlersPass->process(Object) (Line: 141)
Symfony\Component\DependencyInjection\Compiler\Compiler->compile(Object) (Line: 757)
Symfony\Component\DependencyInjection\ContainerBuilder->compile() (Line: 1307)
Drupal\Core\DrupalKernel->compileContainer() (Line: 884)
Drupal\Core\DrupalKernel->initializeContainer() (Line: 466)
Drupal\Core\DrupalKernel->boot() (Line: 656)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

We can solve the problem by applying the following patch:

cd modules/contrib/page_manager
wget https://www.drupal.org/files/issues/2918564-22.patch
patch -p 1 < 2918564-22.patch
diff --git a/page_manager.services.yml b/page_manager.services.yml
index 33bce44..f8fcf78 100644
--- a/page_manager.services.yml
+++ b/page_manager.services.yml
@@ -27,8 +27,10 @@ services:
     arguments: ['@entity_type.manager', '@path.current', '@request_stack']
     tags:
       # Run as late as possible to allow all other filters to run first.
-      - { name: non_lazy_route_filter, priority: -1024 }
+      # @todo Review this when https://www.drupal.org/node/2915772 is done.
+      - { name: route_filter, priority: -1024 }
       - { name: service_collector, tag: non_lazy_route_enhancer, call: addRouteEnhancer }
+      - { name: service_collector, tag: route_enhancer, call: addRouteEnhancer }
   page_manager.route_name_response_subscriber:
     class: Drupal\page_manager\EventSubscriber\RouteNameResponseSubscriber
     tags:
diff --git a/src/Routing/RouteEnhancerCollectorTrait.php b/src/Routing/RouteEnhancerCollectorTrait.php
index 0ca6c44..e91e4a3 100644
--- a/src/Routing/RouteEnhancerCollectorTrait.php
+++ b/src/Routing/RouteEnhancerCollectorTrait.php
@@ -7,24 +7,22 @@
 
 namespace Drupal\page_manager\Routing;
 
-use Symfony\Cmf\Component\Routing\Enhancer\RouteEnhancerInterface;
+use Drupal\Core\Routing\EnhancerInterface;
 
 /**
  * Provides a trait to make a service a collector of route enhancers.
- *
- * @todo Move to Symfony CMF in https://github.com/symfony-cmf/Routing/pull/155.
  */
 trait RouteEnhancerCollectorTrait {
 
   /**
-   * @var \Symfony\Cmf\Component\Routing\Enhancer\RouteEnhancerInterface[]
+   * @var \Drupal\Core\Routing\EnhancerInterface[]
    */
   protected $enhancers = array();
 
   /**
    * Cached sorted list of enhancers
    *
-   * @var \Symfony\Cmf\Component\Routing\Enhancer\RouteEnhancerInterface[]
+   * @var \Drupal\Core\Routing\EnhancerInterface[]
    */
   protected $sortedEnhancers = array();
 
@@ -35,12 +33,12 @@ trait RouteEnhancerCollectorTrait {
    * The order of the enhancers is determined by the priority, the higher the
    * value, the earlier the enhancer is run.
    *
-   * @param \Symfony\Cmf\Component\Routing\Enhancer\RouteEnhancerInterface $enhancer
+   * @param \Drupal\Core\Routing\EnhancerInterface $enhancer
    * @param int $priority
    *
    * @return $this
    */
-  public function addRouteEnhancer(RouteEnhancerInterface $enhancer, $priority = 0) {
+  public function addRouteEnhancer(EnhancerInterface $enhancer, $priority = 0) {
     if (empty($this->enhancers[$priority])) {
       $this->enhancers[$priority] = array();
     }
@@ -54,7 +52,7 @@ trait RouteEnhancerCollectorTrait {
   /**
    * Sorts the enhancers and flattens them.
    *
-   * @return \Symfony\Cmf\Component\Routing\Enhancer\RouteEnhancerInterface[]
+   * @return \Drupal\Core\Routing\EnhancerInterface[]
    *   The enhancers ordered by priority.
    */
   protected function getRouteEnhancers() {
@@ -70,7 +68,7 @@ trait RouteEnhancerCollectorTrait {
    *
    * The highest priority number is the highest priority (reverse sorting).
    *
-   * @return \Symfony\Cmf\Component\Routing\Enhancer\RouteEnhancerInterface[]
+   * @return \Drupal\Core\Routing\EnhancerInterface[]
    *   The sorted enhancers.
    */
   protected function sortRouteEnhancers() {
diff --git a/src/Routing/VariantRouteFilter.php b/src/Routing/VariantRouteFilter.php
index 0c271d8..b23bda8 100644
--- a/src/Routing/VariantRouteFilter.php
+++ b/src/Routing/VariantRouteFilter.php
@@ -1,17 +1,12 @@
 <?php
 
-/**
- * @file
- * Contains \Drupal\page_manager\Routing\VariantRouteFilter.
- */
-
 namespace Drupal\page_manager\Routing;
 
 use Drupal\Component\Plugin\Exception\ContextException;
 use Drupal\Component\Utility\NestedArray;
 use Drupal\Core\Entity\EntityTypeManagerInterface;
 use Drupal\Core\Path\CurrentPathStack;
-use Symfony\Cmf\Component\Routing\NestedMatcher\RouteFilterInterface;
+use Drupal\Core\Routing\FilterInterface;
 use Symfony\Cmf\Component\Routing\RouteObjectInterface;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\RequestStack;
@@ -25,7 +20,7 @@ use Symfony\Component\Routing\RouteCollection;
  * needs to be filtered. Here is where we run variant selection, which requires
  * gathering contexts.
  */
-class VariantRouteFilter implements RouteFilterInterface {
+class VariantRouteFilter implements FilterInterface {
 
   use RouteEnhancerCollectorTrait;
 
@@ -141,9 +136,9 @@ class VariantRouteFilter implements RouteFilterInterface {
           return $name;
         }
 
-        // Restore the original request attributes, this must be done in the loop
-        // or the request attributes will not be calculated correctly for the
-        // next route.
+        // Restore the original request attributes, this must be done in
+        // the loop or the request attributes will not be calculated correctly
+        // for the next route.
         $request->attributes->replace($original_attributes);
         $this->requestStack->pop();
       }
diff --git a/tests/src/Unit/VariantRouteFilterTest.php b/tests/src/Unit/VariantRouteFilterTest.php
index 1664fbb..ea60e91 100644
--- a/tests/src/Unit/VariantRouteFilterTest.php
+++ b/tests/src/Unit/VariantRouteFilterTest.php
@@ -14,7 +14,7 @@ use Drupal\Core\Path\CurrentPathStack;
 use Drupal\page_manager\PageVariantInterface;
 use Drupal\page_manager\Routing\VariantRouteFilter;
 use Drupal\Tests\UnitTestCase;
-use Symfony\Cmf\Component\Routing\Enhancer\RouteEnhancerInterface;
+use Drupal\Core\Routing\EnhancerInterface;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\RequestStack;
 use Symfony\Component\Routing\Route;
@@ -331,7 +331,7 @@ class VariantRouteFilterTest extends UnitTestCase {
     $this->currentPath->getPath($request)->willReturn('/path/with/1');
     $this->pageVariantStorage->load('a_variant')->willReturn($page_variant->reveal());
 
-    $route_enhancer = $this->prophesize(RouteEnhancerInterface::class);
+    $route_enhancer = $this->prophesize(EnhancerInterface::class);
     $this->routeFilter->addRouteEnhancer($route_enhancer->reveal());
     $result_enhance_attributes = $expected_enhance_attributes = [
       'foo' => 'bar',
@@ -375,7 +375,7 @@ class VariantRouteFilterTest extends UnitTestCase {
     $this->currentPath->getPath($request)->willReturn('/path/with/1');
     $this->pageVariantStorage->load('a_variant')->willReturn($page_variant->reveal());
 
-    $route_enhancer = $this->prophesize(RouteEnhancerInterface::class);
+    $route_enhancer = $this->prophesize(EnhancerInterface::class);
     $this->routeFilter->addRouteEnhancer($route_enhancer->reveal());
     $expected_enhance_attributes = [
       'foo' => 'bar',
@@ -436,7 +436,7 @@ class VariantRouteFilterTest extends UnitTestCase {
     $this->currentPath->getPath($request)->willReturn('/path/with/1');
 
     $expected_attributes = ['slug' => 1, '_route_object' => $route, '_route' => $route_name];
-    $route_enhancer = $this->prophesize(RouteEnhancerInterface::class);
+    $route_enhancer = $this->prophesize(EnhancerInterface::class);
     $route_enhancer->enhance($expected_attributes, $request)->willReturn(['slug' => 'slug 1']);
     $this->routeFilter->addRouteEnhancer($route_enhancer->reveal());
 

Drupal 8 Symfony Component Routing Exception RouteNotFoundException Route view.products_list.page_2 does not exist

The website encountered an unexpected error. Please try again later.</br></br><em class=”placeholder”>Symfony\Component\Routing\Exception\RouteNotFoundException</em>: Route &quot;view.products_list.page_2&quot; does not exist. in <em class=”placeholder”>Drupal\Core\Routing\RouteProvider-&gt;getRouteByName()</em> (line <em class=”placeholder”>190</em> of <em class=”placeholder”>core\lib\Drupal\Core\Routing\RouteProvider.php</em>).

Solution:
This is the exception thrown when a route does not exist but you are using it in your twig files or somewhere else. As in the above example find “view.products_list.page_2” in your code and remove it.

<a href="{{ path('view.products_list.page_2') }}">

Then don’t forget to clear the cache.

We hope it is helpful for someone. http://api.symfony.com/3.0/Symfony/Component/Routing/Exception/RouteNotFoundException.html

class RouteNotFoundException extends InvalidArgumentException implements ExceptionInterface
The exception is thrown when a route does not exist.

Admin Language file to make hello world – OpenCart Module Development

Create a language file helloworld.php at “admin\language\en-gb\extension\module\“, here en-Gb is the English language folder but if your store is multi-language then you have to create helloworld.php in another folder also like at “admin\language\OTHER_LANGUAGE_FOLDER\extension\module\“.

Now in helloworld.php, you will define variable that holds the text for that language. Starting defining a variable with $_[‘YOUR_VARIABLE_NAME’] and assign the text for that language.

$_['language_variable']     = 'Text for this language';

Now in the controller, you can do the following:

$this->load->language('extension/module/helloworld');
$data['view_variable'] = $this->language->get('language_variable');

In the view, you will show the text as:

<?php echo $view_variable; ?>

In this way, In the view, you will be able to access the text from the language that the controller file stored as a PHP variable.

For our HelloWorld module of OpenCart module development, the following are the needed text and I have assigned to those variables.

<?php
/**
 * Created by PhpStorm.
 * User: rnepali
 * Date: 10/2/2016
 * Time: 1:45 PM
 */

$_['heading_title']     = 'Hello World Module';

// Text
$_['text_extension']    = 'Extensions';
$_['text_success']      = 'Success: You have modified Hello World module!';
$_['text_edit']         = 'Edit Hello World Module';

// Entry
$_['entry_name'] = 'Enter the Hello World';
$_['entry_title']       = 'Heading Title';
$_['entry_status']      = 'Status';

// Error
$_['error_permission']  = 'Warning: You do not have permission to modify Hello World module!';
$_['error_name']        = 'Module Name must be between 3 and 64 characters!';

%type: !message in %function (line %line of %file) Drupal error

I keep on getting this error logging at watchdog table in the database while loading front end or home page: %type: !message in %function (line %line of %file) Drupal error I spend around 20 min, keep on clicking the “Clear All Caches” button at Performance section. I checked the code and found the following:

function watchdog_exception($type, Exception $exception, $message = NULL, $variables = array(), $severity = WATCHDOG_ERROR, $link = NULL) {

 // Use a default value if $message is not set.
 if (empty($message)) {
 // The exception message is run through check_plain() by _drupal_decode_exception().
 $message = '%type: !message in %function (line %line of %file).';
 }
 // $variables must be an array so that we can add the exception information.
 if (!is_array($variables)) {
 $variables = array();
 }

 require_once DRUPAL_ROOT . '/includes/errors.inc';
 $variables += _drupal_decode_exception($exception);
 watchdog($type, $message, $variables, $severity, $link);
}

If the message is not set then the given above log is set.

Instantly I cleared browser cache and here you go the page is loading well.

Maybe this is the only case for me, but keep on posting if I find any other solution.

The solution Homework 3.1 M101JS: MongoDB for Node.js Developers

Write a program in the language of your choice that will remove the lowest homework score for each student. Since there is a single document for each student containing an array of scores, you will need to update the scores array and remove the homework.

Remember, just remove a homework score. Don’t remove a quiz or an exam!

Hint/spoiler: With the new schema, this problem is a lot harder and that is sort of the point. One way is to find the lowest homework in code and then update the scores array with the low homework pruned.

To confirm you are on the right track, here are some queries to run after you process the data with the correct answer shown:

Let us count the number of students we have:

  1. use school
  2. DB.students.count()

The answer will be 200.

Let’s see what Tamika Schildgen’s record looks like:

  1. db.students.find( { _id : 137 } ).pretty( )

This should be the output:

{
	"_id" : 137,
	"name" : "Tamika Schildgen",
	"scores" : [
		{
			"type" : "exam",
			"score" : 4.433956226109692
		},
		{
			"type" : "quiz",
			"score" : 65.50313785402548
		},
		{
			"type" : "homework",
			"score" : 89.5950384993947
		}
	]
}

To verify that you have completed this task correctly, provide the identity (in the form of their _id) of the student with the highest average in the class with following query that uses the aggregation framework. The answer will appear in the _id field of the resulting document.

db.students.aggregate( { ‘$unwind’ : ‘$scores’ } , { ‘$group’ : { ‘_id’ : ‘$_id’ , ‘average’ : { $avg : ‘$scores.score’ } } } , { ‘$sort’ : { ‘average’ : -1 } } , { ‘$limit’ : 1 } )

Solution:

13

Enter 13 and submit.

Create a file app.js and insert the following code:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/school', function(err, db){
  if(err) throw err;
  var query = {};

  db.collection('students').find(query).toArray(function(err, docs) {
    if(err) throw err;

    var min;
    var doc;
    var value;
    for (var i = 0; i < docs.length; i++){
        doc = docs[i];
        min = -1;
        for(var j = 0; j < doc.scores.length; j++){
           value = doc.scores[j];
           if(value.type === "homework"){
             if(min === -1 || value.score < doc.scores[min].score ){
               min = j;
             }
           }
        }
        console.log("Ant length :" + doc.scores.length + " min : " + min);
        // important: Array.splice need the number of elements to delete...  splice(index, )
        doc.scores.splice(min, 1);
        console.log("Pos length :" + doc.scores.length);
        db.collection('students').save(doc, function(err, saved) {
          if(err) throw err;
          console.log("Doc saved: " + saved);

        });
    }
    //console.dir("Result" + docs);
    console.dir("End");
    return db.close();
  });

});

Now run it with node app.js

Check your result with the following query:

db.students.find( { _id : 13 } ).pretty( )

Result:

{
        "_id" : 13,
        "name" : "Jessika Dagenais",
        "scores" : [
                {
                        "type" : "exam",
                        "score" : 90.47179954427436
                },
                {
                        "type" : "quiz",
                        "score" : 90.3001402468489
                },
                {
                        "type" : "homework",
                        "score" : 95.17753772405909
                }
        ]
}

You can see the lowest homework scores are removed from all documents.

Now again run

db.students.aggregate( { '$unwind' : '$scores' } , { '$group' : { '_id' : '$_id' , 'average' : { $avg : '$scores.score' } } } , { '$sort' : { 'average' : -1 }, { '$limit' : 1 } )

The result will be:

{ "_id" : 13, "average" : 91.98315917172745 }

I have submitted “13” and the answer is correct but if you have any great solution then please let me know as well as if any problem then let me know so that we can solve together.

Final: Question 1 M101JS: MongoDB for Node.js Developers

Final: Question 1

Please download the Enron email dataset enron.zip, unzip it and then restore it using mongorestore. It should restore to a collection called “messages” in a database called “enron”. Note that this is an abbreviated version of the full corpus. There should be 120,477 documents after restore.

Inspect a few of the documents to get a basic understanding of the structure. Enron was an American corporation that engaged in widespread accounting fraud and subsequently failed.

In this dataset, each document is an email message. Like all Email messages, there is one sender but there can be multiple recipients.

Construct a query to calculate the number of messages sent by Andrew Fastow, CFO, to Jeff Skilling, the president. Andrew Fastow’s email address was andrew.fastow@enron.com. Jeff Skilling’s email was jeff.skilling@enron.com.

For reference, the number of email messages from Andrew Fastow to John Lavorato (john.lavorato@enron.com) was 1.Solution: 3  

  • Download the  enron.zip and extract it
  • Now run “mongod”
  • Now import the extracted database mongorestore –drop –db enron dump/enron
  • Now run “mongo”
  • See if Enron database is imported with “show databases”
  • In the list, if you see enron then you are ready to go.
  • Now run “use enron”
  • Then “show collections”
  • You will see messages collection
  • Check your data with “db.messages.findOne()” { “_id” : ObjectId(“4f16fc97d1e2d32371003f02”), “body” : “COURTYARD\n\nMESQUITE\n2300 HWY 67\nMESQUITE, TX 75150\ntel: 972-681-3300\nfax: 972-681-3324\n\nHotel Information: http://courtyard.com/DALCM \n\n\nARRIVAL CONFIRMATION:\n Confirmation Number:84029698\nGuests in Room: 2\nNAME: MR ERIC BASS \nGuest Phone: 7138530977\nNumber of Rooms:1\nArrive: Oct 6 2 001\nDepart: Oct 7 2001\nRoom Type: ROOM – QUALITY\nGuarantee Method:\n Credit card guarantee\nCANCELLATION PERMITTED-BEFORE 1800 DAY OF ARRIVAL\n\nRATE INFORMA TION:\nRate(s) Quoted in: US DOLLAR\nArrival Date: Oct 6 2001\nRoom Rate: 62.10 per night. Plus tax when applicable\nRate Program: AAA AMERICAN AUTO ASSN\n\nSP ECIAL REQUEST:\n NON-SMOKING ROOM, GUARANTEED\n \n\n\nPLEASE DO NOT REPLY TO THIS EMAIL \nAny Inquiries Please call 1-800-321-2211 or your local\ninternationa l toll free number.\n \nConfirmation Sent: Mon Jul 30 18:19:39 2001\n\nLegal Disclaimer:\nThis confirmation notice has been transmitted to you by electronic\nma il for your convenience. Marriott’s record of this confirmation\nnotice is the official record of this reservation. Subsequent\nalterations to this electronic m essage after its transmission\nwill be disregarded.\n\nMarriott is pleased to announce that High Speed Internet Access is\nbeing rolled out in all Marriott hote l brands around the world.\nTo learn more or to find out whether your hotel has the service\navailable, please visit Marriott.com.\n\nEarn points toward free va cations, or frequent flyer miles\nfor every stay you make! Just provide your Marriott Rewards\nmembership number at check in. Not yet a member? Join for free at\nhttps://member.marriottrewards.com/Enrollments/enroll.asp?source=MCRE\n\n”, “filename” : “2.”, “headers” : { “Content-Transfer-Encoding” : “7bit”, “Content-Type” : “text/plain; charset=us-ascii”, “Date” : ISODate(“2001-07-30T22:19:40Z”), “From” : “reservations@marriott.com”, “Message-ID” : “<32788362.1075840323896.JavaMail.evans@thyme>”, “Mime-Version” : “1.0”, “Subject” : “84029698 Marriott Reservation Confirmation Number”, “To” : [ “ebass@enron.com” ], “X-FileName” : “eric bass 6-25-02.PST”, “X-Folder” : “\\ExMerge – Bass, Eric\\Personal”, “X-From” : “Reservations@Marriott.com”, “X-Origin” : “BASS-E”, “X-To” : “EBASS@ENRON.COM”, “X-bcc” : “”, “X-cc” : “” }, “mailbox” : “bass-e”, “subFolder” : “personal” }
  • Now run following query to get the output
    • db.messages.find({“headers.From”:”andrew.fastow@enron.com”,”headers.To”:”jeff.skilling@enron.com”}).count()
  • Confirm you the result, I got “3” as an answer.
final_exam_question_1

The solution Homework 2.3 M101JS: MongoDB for Node.js Developers

You should see four files in the ‘blog’ directory: app.js, users.js, posts.js, and sessions.js. There is also a ‘views’ directory which contains the templates for the project and a ‘routes’ directory which contains our express routes.

If everything is working properly, you should be able to start the blog by typing:

npm install
node app.js

Note that this requires Node.js to be correctly installed on your computer.
After you run the blog, you should see the message:

Express server listening on port 8082

If you go to http://localhost:8082 you should see the front page of the blog. Here are some URLs that must work when you are done.

http://localhost:8082/signup
http://localhost:8082/login
http://localhost:8082/logout

When you login or sign-up, the blog will redirect to http://localhost:8082/welcome and that must work properly, welcoming the user by username.

We have removed parts of the code that uses the Node.js driver to query MongoDB from users.js and marked the area where you need to work with “TODO: hw2.3”. You should not need to touch any other code. The database calls that you are going to add will add a new user upon sign-up and validate a login by retrieving the right user document.

The blog stores its data in the blog database in two collections, users and sessions. Here are two example docs for a username search with password salty. You can insert these if you like, but you don’t need to.

> use blog
switched to db blog
> db.users.find()
{ "_id" : "sverch", "password" : "$2a$10$wl4bNB/5CqwWx4bB66PoQ.lmYvxUHigM1ehljyWQBupen3uCcldoW" }
> db.sessions.find()
{ "username" : "sverch", "_id" : "8d25917b27e4dc170d32491c6247aabba7598533" }
>

Once you have the the project working, the following steps should work:

go to http://localhost:8082/signup
create a user

It should redirect you to the welcome page and say: welcome username, where username is the user you signed up with. Now:

    Goto http://localhost:8082/logout
    Now login http://localhost:8082/login

Ok, now it’s time to validate you got it all working.

From the top of this page, there was one additional program that should have been downloaded:mongoProc.

With it, you can test your code and look at the Feedback section. When it says “user creation successful” and “user login successful”, you can Turn in your assignment.

Solution:

  • Open user.js
  • See changes below //TODO HW 2.3. Changes are done in two places.
var bcrypt = require('bcrypt-nodejs');
/* The UsersDAO must be constructed with a connected database object */
function UsersDAO(db) {
    "use strict";
    /* If this constructor is called without the "new" operator, "this" points
     * to the global object. Log a warning and call it correctly. */
    if (false === (this instanceof UsersDAO)) {
        console.log('Warning: UsersDAO constructor called without "new" operator');
        return new UsersDAO(db);
    }
    var users = db.collection("users");
    this.addUser = function(username, password, email, callback) {
        "use strict";
        // Generate password hash
        var salt = bcrypt.genSaltSync();
        var password_hash = bcrypt.hashSync(password, salt);
        // Create user document
        var user = {'_id': username, 'password': password_hash};
        // Add email if set
        if (email != "") {
            user['email'] = email;
        }
        // TODO: hw2.3
        users.insert(user, function (err, result) {
            "use strict";
            callback(err, result[0]);
        });
        //callback(Error("addUser Not Yet Implemented!"), null);
    }
    this.validateLogin = function(username, password, callback) {
        "use strict";
        // Callback to pass to MongoDB that validates a user document
        function validateUserDoc(err, user) {
            "use strict";

            if (err) return callback(err, null);

            if (user) {
                if (bcrypt.compareSync(password, user.password)) {
                    callback(null, user);
                }
                else {
                    var invalid_password_error = new Error("Invalid password");
                    // Set an extra field so we can distinguish this from a db error
                    invalid_password_error.invalid_password = true;
                    callback(invalid_password_error, null);
                }
            }
            else {
                var no_such_user_error = new Error("User: " + user + " does not exist");
                // Set an extra field so we can distinguish this from a db error
                no_such_user_error.no_such_user = true;
                callback(no_such_user_error, null);
            }
        }
        // TODO: hw2.3
        users.findOne({ '_id' : username}, function(err, user){
            if(err) throw err;
            validateUserDoc(err, user);
        });
       // callback(Error("validateLogin Not Yet Implemented!"), null);
    }
}
module.exports.UsersDAO = UsersDAO;
  • Save and run node js and perform signup and login in the browser if all are OK then open mongoProc and perform “Test” and if all seems OK then “Turn in”. While turning in I see the following screenshot.
m101js-homework_2.3

Let me know if get any problem so that we can solve each other help. As well as if you got any easy way to do it then please let me know.