Getting Started With Drupal Commerce 2.x - Part 1

Drupal Commerce 2.x overview

E-commerce in Drupal 8 is a very interesting topic for many developers and this blog is the right place to start with E-commerce in drupal 8.

Drupal Commerce 2.x is the module for creating online stores of varying complexity. This blog provides an overview of the Commerce 2.x module for Drupal 8.

In this blog, we will be focusing on following things

Installing Drupal E-Commerce 2.x

To install Drupal Commerce, make sure that your server has a Composer dependency manager installed. In Drupal 8, Commerce requires the installation of libraries, which are now installed not manually but with the help of Composer. Make sure Composer installed globally.

You can install Drupal, as well as Commerce together with the dependent modules and libraries with this command:

“composer create-project drupalcommerce/project-base mystore --stability dev”

Everything will be installed to “mystore” folder

Installing Drupal Commerce 2.x on an existing site

We need to do the following steps for Installing Commerce 2.x in existing Drupal 8.x site.

Step 1: Add the Drupal packagist repository which allows Composer to find Commerce and the other Drupal modules. For that run the following command,

"composer config repositories.drupal composer https://packages.drupal.org/8"

Step 2: The following command will he'""lp us to download the required libraries and modules (Address, Entity, State Machine, Inline Entity Form, Profile).

“composer require "drupal/commerce 8.2.x-dev"

Step 3: Enable the all commerce related submodules like  “commerce_product commerce_checkout, commerce_cart” , Use drush or drupal console.

"drupal module:install commerce_product commerce_checkout commerce_cart"

Settings in the admin interface in new Commerce 2.x

Go to the commerce settings (admin/commerce/config).

1. Currency :

It is very easy to use the currency inside and Outside the US.

First, you need to select your store currency (admin/commerce/config/currency). By default, the currency list is empty (you will see the message “there is no currency yet”). The list of currencies needs to be imported. Select the desired ones on the currency import page (admin/commerce/config/currency/import).

 

Import Currencies

Now, at the Currency page, we see a list of currencies.

Currency Page

2. Store :

In the version for Drupal 8, you can create a store or multiple stores , which may vary by products, currencies, tax settings, shipping countries and so on. In Commerce 1.x (Drupal 7) there was no such entity as "store".

You can create your own type of stores (on the admin/commerce/config/store-types page) and add a variety of fields. On the admin/commerce/stores page, click Add new store.

At this step, we configure the store: give it a name, specify its email, country, currency, and other settings.

 

Add A Store

Now, at the Store page, we see our new store.

 

Store Page

 

In this way, in Drupal 8 we can now create multiple stores that have different settings (email, address, default currency, tax settings, etc.).

Each drupal store will have its own cart and checkout. In the second part of this article, next week we will create products.

How does the Media Industry use Marketing Automation for monetization?

The Publishing industry has been proving its mettle.

Media and Publishing are aggregating all kinds of content and reaching it out to people through digital marketing and social media channels. The platforms are plenty and people’s time to focus is less.

The early adopters who belong to the Media domain set the path for innovation in the digital publishing industry.

Marketing Automation is widely used in the retail and e-commerce industry and is making its foray into the digital publishing world. Publishing information on the web requires regular and uninterrupted connection with the readers through a host of devices and channels and mediums, which is scaled up and requires a task of automation that which reacts to a trigger and can be handled to act by itself.

How can Marketing Automation help?

Marketing automation collects user information, couples it up with actions and segments which kind of data can be pushed to which kind of audience. This helps with targeted digital marketing to users. That being said, the main aim of marketing automation in digital marketing is to help with large-scale data analysis, optimization to handle actions like subscriptions and social media interactions.

Marketing Automation will help collect data about Call to Action buttons and actions like a form fill up, subscription, clicking an email to read and aid with marketing efforts. These data can be used by publishers to find out the engagement scores of individuals and help push marketing efforts to customers likewise at an individual level.

Audience development and marketing automation tools can provide greater efficiency, agility, and insight by combining capabilities in analytics, multichannel distribution, and automation. These capabilities allow magazine publishers to optimize their marketing platforms to move faster and more responsively to market nuances. By automating what type of content is sent to certain users (whether they only opened an email without clicking or deeply engaged with email content), publishers can segment their audiences and send more meaningful content to users. That content, because it is more precisely targeted can then spur the actions publishers want (subscriptions, social shares, comments, etc.).

More sophisticated tools, particularly those geared toward B2C segments, are distinguished by their ability to manage huge databases of customer information such as purchase history, demographic information, an online behavior. A publisher might want to compare how a subscription campaign performed among various demographics or regions. Publishers can then orient specific content or campaigns toward individual segments.

Mobile capabilities play a large part in enabling an omnichannel presence. Even a simple email campaign must now accommodate any number of unknown platforms and devices. When evaluating marketing automation or email marketing providers, publishers should particularly explore their mobile testing capabilities, as well as their ability to adapt to swift market changes.

Where do we find the implementations?

Marketing Automation is becoming more complicated and is now incorporating adaptive machine learning. Some of the largest publishers like Time and Sports Illustrated are using same automated tech to buy print ads. This is known as programmatic ad buying and helps cut down on manual work. Which in turn helps with revenue.

Configuration Management in Drupal 8 VS Drupal 7

In Drupal whenever you are making changes in settings configuration changes are made. For example if we enable a permission then its a configuration change. Another example is if place a block in a region it's a configuration change. It is not recommended to make configuration changes directed in live site. 

We make configuration changes in our local environment and then move these configuration to live site. But in some case there are configuration changes as well as content changes , For example Block creation is content changes and placing block is a configuration changes.

Below listed are considered configuration:

  • Content Types

  • Block Types

  • Everything under Admin -> Configuration

  • Everything under Admin -> Appearance,

  • Views.

Below listed are considered content and are not touched by this system:

  • Nodes

  • Custom blocks added on admin/structure/block/block-content

  • Users

  • Content for other entities

One of the best improvements in Drupal 8 is the new configuration management system. This post explains how things have changed from Drupal 7, and how Drupal 8  deals with configuration management.

Configuration in Drupal 7

If you’ve worked on site building or programming in Drupal 7, you have worked with the Features module. 

So we can say that Configuration in Drupal 7 is done by Feature module. Features made it very simple to do this and not have to remember all of the config changes.

Configuration Management System in Drupal 8

The configuration management system in Drupal 8 solves a lot of the problem which we faced with Features in Drupal 7. Below I explain how to use the Configuration Management system in Drupal 8 works.
 

Content in Drupal 8 vs Configuration in Drupal 8

In Drupal 8 is easy to understand what is considered configuration under database change and what is considered content in D8 data content change. In Drupal 8 configuration management system handles is configuration. Here are a few things that below listed  are considered configuration as in YAML file:

  • Content Types

  • Block Types

  • Everything under Admin -> Configuration

  • Everything under Admin -> Appearance,

  • Views.

Here are a few things that are considered content and are not touched by this system:

  • Nodes

  • Custom blocks added on admin/structure/block/block-content

  • Users

  • Content for other entities

Moving content from the environment to environment (not config) requires a different module flow (one example would be the Deploy module) and isn’t handled by configuration management.

Get Familiar with the Drupal 8 Configuration Management System

Hands-on learning are really the only way to understand Drupal 8 configuration management.  Create new sandbox D8 site or using a development D8 site locally so that you can experiment.  Once you have your environment set up work through some common use cases.  

Step #1: Enable Configuration Management and go to Synchronization admin page

Make sure the “Configuration Manager” module is enabled. Clear Drupal cache (drush cr) after you enable the module, which is included in Drupal 8 core.

Go to the Synchronize admin page: /admin/config/development/configuration.It will tell you the config files that have changed between the active configuration (what is in the Drupal DB) and what is staged (in the config YAML files) but also allows you to click on each row to view the exact differences.

Step #2: Export Your Active Configuration

Before you sync configuration between environments, you need to first do a full export of your active configuration by drush cex or by UI. This creates the configuration YAML files in your config_files directory. By default this directory is in your user uploaded directory, you change configuration path in settings.php where all yml will be saved.

There are below listed ways to export your active configuration change to the config YAML files in your sync directory:

  1. Run drush config-export (or drush cex)

  2. Go to the Synchronize admin page, click on the Export tab -> Full Archive and download the exported file. You then need to manually extract the compressed file and move those files into your config_files directory.

  3. Synchronize admin page(/admin/config/development/configuration) should not list any differences between your Active configuration (Drupal DB) and the Staging configuration (config YAML files). At this point, you can commit the config YAML files to your repository.

  4. The Synchronize admin page should not show any differences between your Active configuration (Drupal DB) and the Staging configuration (config YAML files). At this point, you can commit the config YAML files to your repository.

Step #3: Understanding Exporting and Importing Configuration

If you have used Features in Drupal 7, this should be familiar. There are two ways to handle configuration:

Export

This is what you did in Step #2. The configuration defined in your Drupal database and converting it to YAML config files. I suggest using the drush cex command to make this simple.

Import

Export provides a way to go from the Drupal database to config files. Import does the exact opposite. To do this you can click on the “Import All” button on the Synchronization page, or use the drush command: drush config-import (or drush cim).

To understanding the concept is that when you drush cex (export), you are having your config files deleted out and match your Drupal database config exactly. When you run drush cim, you are wiping out the configuration in your Drupal database and having it match what is in your config files exactly. This is important because you need to understand when you should run each of these commands. See the How to Avoid Issues section below for a way to easily avoid this problem.

For example, if you apply a config in the Drupal admin, and then run drush cim you are going to delete out the configuration change you just made in the Drupal admin. If you pull in config file changes from your code repository, apply a change in the Drupal config admin area and then run drush cex you will wipe out the new changes that were pushed to the repository.

You can refer drush based workflow doc page for more info.

Step #4: Enjoy your Drupal 8 configuration

At this point, your active configuration should 100% match your staging configuration. It is time to understand what happens when your Drupal config changes and when your staging config files change.

Drupal Config Changes (Drupal database)

Let’s make a very basic change in our Drupal DB configuration and see what happens.

(1) In the drupal admin area, make a simple config change. For example, go to /admin/config/system/site-information and update the Site Name field.

(2) Go back to the Synchronize admin page and notice what happens:

Configration changes in Drupal

It is telling you you're active and staging config do not match. Click on the View Differences button to see what has changed:

active changes in Drupal Configuration

(3) On the left, it is telling you what was changed in your Drupal DB configuration. On the right, it is showing you what is defined in the config files (staged).

(4)  when you run drush cex or drush cim is the best way to understand how things work. If you export what is in your active configuration will also be in your staged configuration (which is probably what you want in this case). don't , the change you just made that will wiped out and it will go back to what is in your configuration files.

Note: This illustrates the idea that if you pull in changed config files and update Drupal config in the admin right after that, you are going to be in a pickle in that you will either have to wipe out the changes in the config files or wipe out the changes you just made in the Drupal config! Later in the article, I document a process in avoiding this scenario.

Staged Config Changes (config YAML files)

Now we need to see what happens when the config files are changed. This would happen if someone exported new config they made locally and pushed to the repository. In this case, you usually want to make sure your Active configuration gets updated with what is in the config files so you don’t wipe out their changes.

(1) Make a same change by Drupal admin, directly to the config files. Now you don’t necessarily have to get comfortable working with the config files directly, but it does help to have a basic understanding of how the YAML works.

(2) Go to your config_files directory and open the system.site.yml file. Change the value under the “name” key to something different.

(3) Go to the admin synchronization page and click the View Differences button. It should look like this:

Differences in active and staging environment

Notice how the change, in this case, appears in the Staged column? That is because the change was done in the configuration files and not in the Drupal admin area.

(4) You need to run drush cim to get your active configuration from your config files. If you run drush cex at this point, it will wipe out what was in the config files.

Object-Oriented Programming Concepts in PHP - Part 2

In the previous article of Object Oriented programming concepts in PHP,  we learned to create a class, define objects for the class and create methods. We also learned about different topics of object-oriented programming like inheritance, interface, and abstraction.

In this article we will deal with php's Magic methods. Php classes are some predefined functions. Magic methods starts with the prefix __, for example __call, __get, __set. There are various magic methods in php. Here we will discuss some of the following magic methods of php which will be use in object oriented programming. First of, let us review some important magic methods with short description:

Description_Magical_Methods

Magic Methods:

The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(),__invoke(), __set_state(), __clone() and __debugInfo() are magical in PHP classes.

We cannot have functions with these names in any of our classes unless we want the magic functionality associated with them.

Now Let us discuss the important Magical Methods,

Constructors:

    A constructor is the first function to be called even if n number of functions are there in the class. Constructor need not be initialized and called explicitly. It is automatically called when the object is created with the help of the new operator.

    The constructor allows sending the parameter to the class when the object is created.

Examples for the constructor:

Output:

Indian Tiger

An example of constructor in INHERITANCE:

Output:

Calling parent class constructor

Calling parent class constructor

Calling child class constructor

Destructors:

__destruct is the keyword for the destructor. A destructor is called automatically when the object is destroyed. The destructor is automatically called by the garbage collector when the memory allocated for the variable or the object holding the resource is no longer needed.

Example:

Output:

Calling the constructor

Calling  Destructor  object

__get():

    __get() is utilized for reading data from inaccessible properties.

    It accepts one argument, which is the name of the property.

    It should return a value, which will be treated as the value of the property.

Example:

Note that our student class has $Age commented out, and we attempt to print out the Age value of $obj. When this script is called, $obj is found to not to have an $Age variable, so __get() is called for the Student class, which prints out the name of the property that was requested - it gets passed in as the first parameter to __get(). If you try uncommenting the public $Age; line, you will see __get()is no longer called, as it is only called when the script attempts to read a class variable that does not exist.

__set():

    __set() is run when writing data to inaccessible properties.

    It accepts two arguments, which are the name of the property and the value.

For Example:

In that script, $mailid is commented out and therefore does not exist in the mytable class. As a result, when $mailid is set on the last line, __set() is called, with the name of the variable being set and the value it is being set to be passed in as parameters one and two respectively. This is used to construct an SQL query in conjunction with the table name passed in through the constructor.

__toString():

    The __toString() method is called when code attempts to treat an object like a string.

    It accepts no arguments and should return a string.

    This allows us to define how the object will be represented.

For Example:

Output:

Hello, how r u

Cloning Objects:

Object cloning is the act of making a copy of an object.When the object is created with the help of new keyword and assigned the object created to a new variable the object reference will be copied but not the value stored in that object. And now if we want to change the value of the object created the copied object variable will also be affected. Similarly, if we change the copied object, the created object data will be affected. So to solve this problem we will use the concept of cloning

For example Copy of the object

Output:

test object
(
   [a] => no arun
   [b:test:private] => technology
)

test object
(
   [a] => no arun
   [b:test:private] => technology
)

test object
(
   [a] => arun
   [b:test:private] => technology
)

Implementation of clone object in PHP:

Object cloning can be implemented by using clone keyword.

Example: Implementation of Object Cloning in PHP

Output:

test object

(

[a] => no arun

[b:test:private] => technology

)

test object

(

[a] => no arun

[b:test:private] => technology

)

test object

(

[a] => arun

[b:test:private] => technology

)

Object cloning with __clone magic method:

Suppose we need to change the value of property in clone object.The behavior of the clone object has changed by using magic method __clone in php.

Example: Object cloning with magic method __clone

Output:

test Object

(
   [a] => no arun
   [b:test:private] => technology
)

test Object
(
   [a] => no arun
   [b:test:private] => technology
)

test Object
(
   [a] => c
   [b:test:private] => technology
}

In this article we explained the important concepts of PHP OOP called Magical Methods.The PHP magic methods are used to react to different events and scenarios that your object might find itself in. Each of these magic methods are triggered automatically, so in essence, you are just defining what should happen under those circumstances. Hopefully each of the examples I’ve presented in this blog will help to you.

 

 

How Can Publishers Improve The Context of Ads

There is always a tug of war between buyers and sellers and the Media and Publishing industry is no different. Publishers are always on a lookout to increase their conversion sales and sell more, whereas the customer wants the most value from his buying decisions. With the onset of the digital era, the switching cost has gone down,  the amount of data available to the consumer is unlimited, and gaining the audience’s attention to the relevant content has become a challenge.  

How to stay relevant?

When everyone is sharing content, and telling stories about their brands, the only thing which can differ and give your content a boost is contextual targeting. It has become essential to ensure, the context of your advertising; be a stand alone differentiator with respect to other ads. By backing on data and insights, publishers can make better decisions about how the audience can be kept engaged along with where and when the audience is ready to make a buying decision. Using technology for audience targeting is meaningful, giving you an opportunity you to reach your audience at the right time and place.

What is contextual advertising?

Contextual advertising is often referred to as target advertising i.e. targeting to a specific user. Search engine advertising, Google Adsense are few examples of the same. Advertisers work on ad targeting to influence consumer decisions by grabbing their attention to the messages which are relevant to them, giving them a more customised and personalised experience. Thus, for contextual targeting, it becomes necessary to understand the context, it could be location, weather, traffic etc.; to deliver a good experience. Aggregating contextual data on users allows better ad targeting, relevant content and higher value ad inventory for publishers.

Contextual Targeting

 

Where to utilize contextual advertising?

Advertisers are doing ad targeting using cloud technology. For instance, location data from mobile devices enables publishers to know the interests and behavior of their targeted audience at a specific time and place, this helps them to share the right content at the right time. Then this data, can be used to do ad targeting and to create audience personas based on demographic data like income, education, gender etc and combine it with the behavioural aspect;  such insights enable advertisers to buy media algorithms to increase the value of ad inventories, and enable them in delivering valuable content along with greater conversions.

For example, if someone has a time constraint and is looking for directions to a particular location on their phone, a mobile advertisement at that moment will not be very effective as the user attention will be more keen on reaching the place on time. However, for a person who is waiting in a bank queue is more likely to have a purchase intent on seeing the ad. Thus, understanding the behavior with insights is one step deeper to these target advertising analysis, and enables one to capture the potential audience.

location used for context ad targeting

 

Geo-fencing allows showing advertisements within a certain geographical area. Many advertisers are already using this ad targeting technology to their advantage. For instance, one of the stores in Guatemala, uses technology to win over the competition. When customers with a smartphone enter the store, they receive a coupon for a discount—at a competitor’s store nearby. The coupon expires after a specific length of time, thus, trying to cash on the impulsive buying behavior using location and cloud technology. This is how technology and data is being used for audience targeting.

What to do next?

Publishers and advertisers should rethink their strategies and take a deep analysis as to where are the places where consumers encounter advertisements and then focus on capturing the micro-demographics of users and create individual personas to be able to target users down to a precise location and behavior to encourage participation and engagement. Mobile phones have created a revolution and enabled real-time tracking, giving advertisers enough real-time data to take advantage of context ad targeting. Advertisers should offer consumers value for sharing their data and build a barrier to value their rights to privacy so that the consumer sees the worth of sharing content. A highly engaged and a segmented audience is an opportunity for advertisers to seize with targeted advertising.

How to create a Drupal Entity programmatically in Drupal 8

Entities have been introduced late in Drupal 7. Drupal entity is an instance of a particular instance type. For example, the entity type for taxonomy terms is named taxonomy_term and the class name Term. We include a class like  Drupal\taxonomy\Entity\Term. Here taxonomy is a core module name, and Term is the class name of Entity.

Related: How to Create Custom Entity in Drupal 8 for Content Management

A. How to create a user programmatically.

The fields to be created are as follows:

  1.  Username
  2.  Email address
  3.  Password
  4.  Status
  5.  Roles
  6.  Picture
  7.  Timezone

If you want to create a Drupal user programmatically we can create it the way as given below:

a) This is the first method

  The output is shown below:user create

Related: How to Create Configurable Block programmatically In Drupal 8

The use of Drupal\user\Entity\User; is to include the class User.

User::create()is used to create a user where it takes the details about the user.

Here name is the username whose account is to be created.

Here mail is the email id of the user and pass is the password for the user.

The status tells you if the user account is active or blocked. If it is 1 then the user account is active and if it is 0 then the account is blocked.

The roles mention which roles is given to the user. To give the user more than one role simply pass an array of roles.

The timezone mentions a timezone set for the user.

The user_picture accepts the image’s file id to get the user image. To get the file id we have passed a static image here in $file_image='/var/www/html/drupal/sites/default/files/2017-04/images.jpeg'; The file_get_contents() reads a file into a string. $directory is the name of the folder where you want to save the uploaded image. file_prepare_directory($directory, FILE_CREATE_DIRECTORY); The above line creates the folder if it doesn't exist. The file_save_data saves the files details. The first parameter takes the file content, the second parameter takes the name of the folder you want to save your image and the name of the file, the third parameter tells you to replace the file if it already exists.

b) This is the second way to create user  

The first parameter of entity_create accepts the entity type that we want to create and the second parameter accepts an array of values to be used to create that entity. The user created is saved to finally create the user.

Related: How to add Product Programmatically to Drupal Commerce Cart

B. How to create a node programmatically

If you want to create a drupal node programmatically we can create the way as given below:

a) This is the first way to do this:

 

node create

 This will be the output.

Here the use \Drupal\node\Entity\Node; is used to insert the class Node.

Node::create() is used to create a node.

Inside Node::create() the node details is passed.

The type tells you the content type whose node is to be created.

The title is the node title, body is the body part of a node.

The field_mail is the email id to be entered if you have a field for email.

The field_link allows you to add a link if you have any link field and field_date holds the value of date field.
 

b) This is the second way to create the node   

  The entity creates function takes two parameters where the first parameter tells you which entity to create and the second parameter should be an array of the node details. 

C. How to create a taxonomy term programmatically

If you want to create taxonomy term programmatically we can create the way as given below:

a) This is the first way to create term

  The output is shown below:

term create

   In above code use Drupal\taxonomy\Entity\Term; is used to insert the class Term

  Term::create has been used to create the term where Term is the class name.

 

Here name and vid are machine names where name represents the name of the new term you want to create, and vid is the name of the taxonomy term whose term you want to create.

b) This is the second way to create a term 

The entity create function takes two parameter where the first parameter tells you which entity to create and the second parameter should be an array of the term details.

 It should contain the term name and the taxonomy name whose term you want to create. You can add the term description but it’s optional.

D. How to create a custom menu

Create a form inside the Form folder as given in the code below.In Drupal 8 modules we write a form inside a Form folder.

Create a routing file which is module_name.routing.yml  Here menu.route is the routing name and _form is the path of the form. 

In module_name.links.menu.yml file write the code for the menu as shown below:

  links.admin is the name of the menu.

The title will appear as the menu name.

The parent tells you the place where the menu will be created like system.admin will create the menu in the main navigation. If the parent is not mentioned then the menu will be created in the tools.

Related: How to create a custom block programmatically in Drupal 8

  The route name is the name of the routing file of whose menu you want to create.

The output is as follows.

menu

  Here TechX is the menu created.

E. How to create a custom permission

 Taking the example of the module above, create a file and name it as module_name.permissions.yml

  Write the following code into it:

 Here 'Menu permission': is the name of the permission that we mention in the routing file ,

 The title gives you the name displayed in the drupal's permissions page. In routing file under _permission we mention this permission name. So whichever role has this permission can view the form.

This is how drupal permissions are given to a particular page when you don’t want to show the page for every user or role.

So here we have learnt how to create entities in drupal 8 programmatically. In drupal 8 you can create node, user, taxonomy without code, but sometimes due to various project requirements and we need to create these programmatically.

Related:

How to send mail programmatically in Drupal 8

How to add Custom JS / CSS to Drupal 7 page in theme for a better user experience

Adding JS adds dynamic presentation effects to a theme for a better user experience.

In One of the project when i had been asked to display a custom error message to the User login page, when user tried with 3 or more failed attempt. On the other hand we can handle the error using form_set_error or drupal_set_message. What if we want to include that error message to be displayed on specific position.there comes add_js into picture. I have created a hook_form_alter inside that called a custom form validation. Under that custom form validation by checking the user login count, calling an js to the user page. Sleek and simple way to do the JS

When we work with theming or module development we required to add  custom js / css to our theme or module and Adding own CSS/JS to the Drupal page is easy and multiple approach is available in drupal to do this. But the best approach to do is to get the exact requirement and understand what is best way to handle css/ js for that period of time.

Below are the list of approach

  • drupal_add_css(), drupal_add_js()
  • including in .info file
  • [‘#attached’] attribute
  • drupal_add_library()
  • hook_css_alter(&$css), hook_js_alter(&$js)
  • drupal_add_html_head()
     

Including as html in .tpl.php
 

1. drupal_add_css(), drupal_add_js()

In Drupal, drupal_add_js() & drupal_add_css() are functions to add JS/CSS to the module or theme layer. This method is used by most of the developer. Which is easy to use and can be inserted wherever you want, can be inserted online, can be added file as cache easy to find documentation. On the other hand it can be found anywhere in the codebase where it is difficult to search sometimes and you are not expecting to be there. Adding multiple file can lead to a big mess. And also require proper naming convention if you make change in js or css file. You need to add the same name to everywhere in  the code where you have used drupal_add_js() & drupal_add_css().

drupal_add_js(drupal_get_path(‘module’, ‘example’) . ‘/example.js’);

drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');

drupal_add_css(drupal_get_path('module', 'example') . '/example.css');

drupal_add_library('example', 'drag-and-drop');

 

2. including in .info file

Custom Javascript file can be added to module/theme under info file. It ‘s always a better way to let the other Developer know how many more  file you are going to attached with your module or theme. Once it is has been declared & added to module/ theme file. It automatically get added to all the page. No need to declare in any of the preprocessor. Most of the themer use this approach for theming. On the other hand unusual css /js get added to un required pages.  No control over addition of css/ js to specific page. Can not be removed or set weight in .info file.

name = My theme

description = Theme developed by me.

core = 7.x

engine = phptemplate

 

scripts[] = mytheme.js

3. Form API [‘#attached’] Property

On of the best way to make sure which files you are going to add. Works great with CSS, JS, library. Easy to include in any of the drupal form and we have ability to add multiple files. It can be used any kind of attached data. A keyed array of type => value pairs, where the type (most often 'css', 'js', and 'library') determines the loading technique, and the value provides the options presented to the loader function.

$form['#attached']['css'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.css',
);
$form['#attached']['js'] = array(  

    drupal_get_path('module', 'ajax_example') . '/ajax_example.js',

);

4. drupal_add_library()

Adding a multiple JavaScript or CSS files at the same time.

The library defines collection of JavaScript and/or CSS files, optionally uses settings, and optionally requiring another library. For example, a library can be a jQuery plugin, a JavaScript framework, or a CSS framework. This function allows modules to load a library defined/shipped by itself or a depending module, without having to add all files of the library separately. Each library is only loaded once. It allow you to reuse styles/scripts on different pages, Path and file names are stored in one function, easy to include in multiple files. On elibrary can use other library too. On the other side a Bit more code to write. And include all the files in library.

Parameters

$module: The name of the module that registered the library.
$name: The name of the library to add.
$every_page: Set to TRUE if this library is added to every page on the site. Only items with the every_page flag set to TRUE can participate in aggregation.

Return value

TRUE if the library was successfully added; FALSE if the library or one of its dependencies could not be added.


5. hook_css_alter(&$css), hook_js_alter(&$js)

hook_css_alter() is designed to act on .css file before they are being included on the page .  using this hook you can easily stop a .css file or group of files from being added to the page.


function demo_css_alter(&$css) {

  $path = drupal_get_path('module', 'node') . '/node.css';

  unset($css[$path]);

}

The $path variable you see above stores the path to the node.css file found in the Node module folder and is used in the unset() function to identify which array element we want to unset.

Parameters:

$css: An array of all CSS items (files and inline CSS) being requested on the page.

hook_js_alter() Perform necessary alterations to the JavaScript before it is presented on the page.


function hook_js_alter(&$javascript) {

  // Swap out jQuery to use an updated version of the library.

  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';

}

Parameters:

$javascript: An array of all JavaScript being presented on the page.


These above two hooks help you to rearrange elements by weight. we can delete files you don’t need before aggregation. Easy to replace path to a specified file. And Possible to re configure the aggregation. On the other hand Adding files here is possible but a bad choice and you end up by  messing up with files here.


6. drupal_add_html_head()

This is not the  recommended way to adding your custom css/js to the page as Using this functionality we adds output to the HEAD tag of the HTML page.This function can be called as long as the headers aren't sent. Pass no arguments (or NULL for both) to retrieve the currently stored elements. It’s is very difficult for understand where the code is included.


/**

 * [THEME] Preprocess function for the html theme hook.

 */

function themename_preprocess_html(&$variables) {

  $front_page = drupal_is_front_page();

  if ($front_page) {

    $variables['head_title'] = 'Jesús Heredia | Web Developer';

    // Add the description meta tag to the header

    $meta_description = array(

      '#type' => 'html_tag',

      '#tag' => 'meta',

      '#attributes' => array(

        'name' => 'description',

        'content' => "Jesús Heredia's personal website. Web Development on HTML5, CSS3, JavaScript, PHP, and Drupal.",

      )

    );

    drupal_add_html_head($meta_description, 'meta_description');

  }

}

Syntax: drupal_add_html_head($data = NULL, $key = NULL)


Parameters

$data: A renderable array. If the '#type' key is not set then 'html_tag' will be added as the default '#type'.

$key: A unique string key to allow implementations of hook_html_head_alter() to identify the element in $data. Required if $data is not NULL.
 

7. Including as html in .tpl.php
Yes we can add as html file in .tpl.php or printing it. Hope those methods come in handy for you. Make sure to use them in dependence of conditions you meet.

Conclusion: I personally feel to use drupal_add_library and [‘#attached’]. The form attached is really awesome and it’s very easy to understand what’s going on without scrolling through all the code.If you have any other idea just share across us over comment. want to find out more.

How Heatmap Tracking Tools can increase website traffic using website analytics for digital publishers?

Most of the media companies are competing in content marketing in the online world and battling with the question, whether their content is faring well than the others. Analytics and metrics give deep insights on number of visits, visitors, duration of a visitor’s visit, the entry and exit points, but misses on the granular data such as the engagement level and interaction on the content page.

To measure the missing connect, publishing companies have moved towards heatmap tracking tools; to understand how people interact with the content on the website. Heatmap is a visual overlay that has the appearance of an infrared display with colour variations indicating high and low levels of activity. These heatmap tracking tools are very useful when preparing website navigation, layout and  in designing user friendly interface.

Heatmaps can measure - click, move and scroll, that means it can track where users have clicked on a page, how far they have scrolled on a page, and have also been used to display the results of eye-tracking movements and these results are displayed in real time.

When used along with other analytical tools, these heat map tracking tools give a good result in optimising website, understanding the aggregated behaviour of site visitors on content,  generating content performance and driving higher conversion rates.

The most popular website heat maps used by media companies are the following:

1. Crazy Egg: Crazy Egg is one of  the most popular heat map tools. It offers click, mouse cursor, and scroll heatmaps. It offers another useful feature called confetti heat map. Confetti heatmap divides the data into traffic sources, enabling the user to figure out where the most profitable traffic is arriving from. The clicks can be separated by a number of variables, such as device, region, or campaign, thus, giving a better insight. WPMU Dev used Crazy Egg’s confetti report to see how their visitors were interacting with content on their product page and identified the important parts of the navigation menu and redesigned the product page. 

Crazy Egg also gives a comparison of mobile versus desktop visitors to see how the two different groups interact with the content. Unlike other heatmap tracking tools, it does not limit usage to per site, this means one can use the same account on multiple websites. What goes amiss here is that there is no screen-capture recording of the visitors and they do limit the number of active pages. However, Crazy Egg has been utilised by most companies to drive sales. For instance, Softmedia, a world’s leading provider in penny auction software used Crazy Egg heatmaps to identify problem areas on their website. They successfully identified distractions that were preventing visitors from completing  the desired actions. After removing these, conversions increased by 51%, and also improved their user interface.

2. Mouseflow: Mouseflow is another easy to use heatmap tool for WordPress users. Mouseflow offers click, scroll, movement and attention heatmap. It also offers recording of website visitor activity. Sticker Gigant, an emerging social media beauty brand from Germany, approached Mouseflow on relaunch of their website to engage users better and to drive performance. With the help of Mouseflow, Sticker Gigant was able to identify issues in the user interface immediately after relaunching the website. After relaunch, Mouseflow improved the average shopping basket value by 78%, increased orders with iOS devices by 26%, and raised cross-selling with first orders by 18%. These numbers are evidence of how effective heat maps are and these are great tools for tracking website traffic.

Another useful feature offered by Mouseflow is form analytics, which allows one to see why users are abandoning forms. It also tracks funnels, custom funnels can be setup to understand the different sources of traffic and their behaviour. Media companies using Wordpress tend to use their WordPress plugin as it provides support for WordPress multi-sites, which lets one watch the analytics from various domains through a single source; giving insights not only on visitor demographics but also visitor activity.

3. Inspectlet: is a very powerful session recording and heatmap service. It displays how people interact on web-pages employs eye-tracking, shows clicking as well as scrolling on the heatmaps. Their conversion funnel analytics is ideal for those selling products online and their engagement heatmaps are also impressively detailed, tracks all interactions including visitors comments. They also offer conversion funnel analytics with  powerful tagging filtering feature along with form analytics to understand and optimise lead generation. This feature has been helpful for those driving multiple websites in e commerce.

Blue Kangaroo, a social retail website, features trending products and deals from thousands of stores. Prior to Inspectlet, Blue Kangaroo relied solely on analytic charts and graphs to better understand their users. With Inspectlet, Blue Kangaroo could compare how much time their audience was spending on similar products. Taking these inputs into account, Blue Kangaroo improved their algorithm and design, leading to an 84% increase in total clicks.

Heatmap tracking tools give detailed overview of how well users are engaging with the website along with how these are used as tools for tracking website traffic. Heatmaps show both - qualitative and quantitative behavioural metrics.

Media companies are using these heat maps not only to understand the user interface but also using it to get a broader view social media impressions. For, instance-'one million tweet map', is used to see how often people are tweeting around the world and the top trending topics they're tweeting about. Such heat maps provide an idea of when and where specific conversations are/were at their peak. It helps companies to track trending conversations, understand where exactly these conversations are taking place, also use these tools for tracking website traffic as well as track the success of a particular online campaign.

The visual representation makes it easier to analyse the data and gives a direction  to improve search rankings, performance and deliver better user experience.

Discalimer : Image used above is no a real time tracked one, but just for reference.



 

 

Object-Oriented Programming Concepts in PHP - Part 1

PHP is a server-side scripting language, mainly used for web development but also used as a general-purpose programming language. Object-Oriented Programming (PHP OOP),  is a type of programming language principle added to php5, that helps in building complex, reusable web applications.

In this blog, we will be explaining some of the Object-Oriented Programming concepts in PHP with some examples.

The  PHP Object-Oriented Programming concepts are:

 

  • Class 
  • Objects
  • Inheritance
  • Interface
  • Abstraction
  • Magic Methods

Class  & Object:

  • Class is a programmer-defined data type, which includes local methods and local variables.
  • Class is a collection of objects. Object has properties and behaviour.
  • First we have to define a php class, where classname should be same as filename.

Example for simple class:

 

 

Output:

Drupal book

900 Rs/-

In the basics of object-oriented, let see how to define a class and create an object:

Creating Objects in PHP

When class is created, we can create any number of objects in that class. The object is created with the help of the new keyword.

Calling Member Function

When the object is created we can access the variables and method function of the class with the help of operator ‘->, accessing the method is done to get the information of that method. Also, look into how we can access object properties via variables

 

Output for the above code 

Samsung S8

Iphone S7

MI4

90000

65000

15000

Inheritance

When the properties and the methods of the parent class are accessed by the child class, we call the concept has inheritance. The child class can inherit the parent method and give own method implementation, this property is called overridden method. When the same method of the parent class is inherited we call as inherited method. Now let us see types of inheritance supported in Object Oriented Programming and corresponding Php inheritance examples.



 

 

 

 

Types Of Inheritance

  1. Single Level Inheritance
  2. Multilevel Inheritance

Single Level Inheritance:  In Single Level Inheritance the Parent class methods will be extended by the child class. All the methods can be inherited.



Single Level Inheritance

Single Level Inheritance

Example for Single Level Inheritance

 

Output

Hi : Pavan

I am from valuebound

Hi: savan

I am from ABC

MultiLevel Inheritance :  In MultiLevel Inheritance, the parent class method will be inherited by child class and again subclass will inherit the child class method. 

MultiLevelInheritance

 

Output

Class A is 80

Class B is 50 

Class C 20

 

INTERFACES:

  • An interface is a description of the actions that an object can do.
  • Interface is written in the same way as the class the declaration with interface keyword.

Rules of Interfaces:

  • All methods declared in an interface must be public; this is the nature of an interface.
  • All methods in the interface must be implemented within a class; failure to do so will result in a fatal error.
  • The class implementing the interface must use the exact same method signatures as are defined in the interface
  • Interfaces can be extended like classes using the extends operator.

Example for the interface class

Output:

Describing Mango tree

2) Interface can be extended with another interface using extends keyword

 

Output:

division of 10/2 is 5

multiplication of 2*3 is 6

Note on Interfaces:-

  • We cannot create objects to interface, but the class implementing the interface can have objects
  • We cannot define a variable in an interface.
  • If we extend interface all the methods of the interface must be implemented in the child class.

 

Abstract Classes:

  • An abstract class is a class that contains at least one abstract method. The abstract method is function declaration without anybody and it has the only name of the method and its parameters.
  • There can be any number of methods in the class and we have to declare the class as abstract only when there is an abstract method

Example for Abstract class



Output for the above code is:

Maruthi Suzuki

720000

Hyundai

300000

Notes on Abstract classes:

  • Objects cannot be created for the abstract classes.
  • If a class has only one method as an abstract, then that class must be an abstract class.
  • The child class which extends an abstract class must define all the methods of the abstract class.
  • If the abstract method is defined as protected in the parent class, the function implementation must be defined as either protected or public, but not private.
  • The signatures of the methods must match, optional parameters given in the child class will not be accepted and error will be shown.
  • Abstract classes that declare all their methods as abstract are not interfaces with different names. One can implement multiple interfaces, but not extend multiple classes (or abstract classes).

Now Let us see the difference between abstract class and interface.

Abstract class Interface
It can have constants, members, method stubs (methods without a body), methods It can only have constants and methods stubs.

Methods and members can have public or protected  visibility

 

Methods of interface should only be public not any other visibility

The concept of multiple inheritances not supported.

 

An interface can extend or a class can implement multiple other interfaces.

 

Child class must implement all the abstract method of parent class when extend keyword is used.

 

No need of implementing methods from parent interface when interface  is extending another interface

In the end, now we are able to create a class, define objects for the class, and create methods. We also learned about different topics of object-oriented like inheritance, interface, and abstraction. The basic concepts of OOP are explained in this blog. 

Related: Understanding PHPUnit and How to write Unit test cases

 



Revolutionize Your Business: Embrace PHP OOP for Growth

 

How to create custom Form with CRUD (Create, Delete, Update) operations in Drupal 8

Custom form with CRUD Operations is basically building the form with different fields like UID, Name, Mobile Number, Address, Email id etc. The CRUD operations for these fields is Deleting the value of the fields from the database or updating the existing value with new value, and printing the updated value. 

How To Create a Custom form with CRUD Operations?

To create a custom form with CRUD Operations, we need to follow the following folder structure as shown in the image. To perform the same operation of crud in drupal we need to follow the following folder structure.

CRUD Folder Structure



 

The data from the database will be displayed in the form of a table and the table will contain operations as a new column. The role of operations column is to perform edit(update) operation or the delete operation. The edit operation is used to update the present value into new values and delete operations is used to delete the entire row. The following files and procedures help us to create a custom form with CRUD operations. Create the files as shown in the image.

mydata.info.yml:

The .info.yml files is most important part of Drupal Modules. The .info.yml file is a collection of static text file, used to define and configuring a module. First, we have to create info.yml file which contains metadata about the project like the name of the module, description, core, package.

mydata.install:

mydata.install helps to create a table in the database. I have created a table called mydata in the database.hook_schema helps to store the values into the database. In our custom form the crud database will be stored in mydata as the table name. If the value is stored in the database, it helps in performing CRUD operations,like edit or delete. I have stored the fields as name, id, mobile number, email, age gender. Id is autoincrement with the help of serial type.

mydata.routing.yml

mydata.routing.yml helps to transfer the function to the Controller to display of data in table format, to create form and placing that form in blocks. When '/mydata/hello/table' is passed to the url the Controller  DisplayTableController is called and the controller will display the data from database in table format. Similarly when the ‘/mydata/form/mydata’ is passed to the url the form containing credentials like name, id , age etc is shown to the user. The user has to enter the details.



When the path  '/mydata/form/delete/{cid}' is passed to url DeleteForm.php is called. By this file you can delete the fields present in the database row by row.

Controller

In the src/Controller create a file called 

DisplayTableController :

In this file, we will display the output in the table format. We have used the standard way of displaying the values of the row in table format.

The code for displaying the value in table format. The $header_table must be defined, like what are the column values that need to be displayed in the table format.

Form

In the src create a folder called Form, In the form folder, we will create a file which will help to create form fields like Textfield, checkbox, select list, number etc..

MydataForm:

In this file, we will create the form fields for  UID, Name, Mobile Number, Email, age etc. For more info on form API, visit https://www.drupal.org/docs/8/api/form-api/introduction-to-form-api . The complete code for the Mydata form is shown below

In the above file we have performed both Insert and update operations. If the user clicks the edit operations then it will call the update functions or it will be insert operation.We have used three methods to perform the operation

  • Buildform: It is the method which is used to construct the form with different types like text field email, select checkbox etc
  • ValidateForm : In this method we provide validation conditions for the form, that has to be validated before the form values get submitted
  • Submit form : In this method the values will be submitted to the database so, it can be retrieved. 

   2.  DeleteForm.php :

In this file we will perform delete operation. I have followed certain standards to delete operation, we can also user db_delete operation. The complete code for the delete operation is shown below

Note : cid is the current value form the url and cid is stored in this->id(current id).

BLOCK



1 MydataBlock:

This block helps to place the form fields anywhere in the UI. Placing the block can be done by going to admin/Structure/block and placing the block in any of the regions. The code of MydataBlock is shown below

The output of the above module is shown below

CustomForm

The above screenshot displays all the form fields that are to be entered by the user .It is a block that is placed 

CrudOperationPage(output page):  

It display the option for delete or edit

Output of CRUD

 

Reference : https://github.com/pavanBS/drupal-module-crud

 

 

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch