How to push clean code by using git pre-commit hook

Pushing clean codes is not every one cups of tea, it needs extensive knowledge and practice. Before a website go live, it needs to pass certain standards and checks in order to deliver quality experience. Certainly, a clean website is a demand of almost every client and it should be. 

In this blog post, you will learn why we need to implement git pre-commit hook? how it works? Simultaneously, we will also attempt to implement working examples in order to have better understanding.

Why we need to implement git pre-commit hook

Any website going live should pass certain standards and checks. If the web is built on any framework, then these checks are mandatory. How to ensure all developers are committing clean code? One way is to do code review, but this is manual and we can’t ensure all the issues are caught up. Another way is to set up continuous integrations (CI), where we can do these checks as automated jobs. In both ways, we can catch this up soon before pushing the code by any developer using git pre-commit hook.

Do you know git supports hook? A list of supported hooks and sample code can be found in ‘.git/hooks’ directory. You can read more about each git hooks here. In this article, we will explore about git pre commit hook.

How git pre commit hook script works

Whenever a git commit is performed, git pre commit hook script will be executed where we can do syntax check, presence of any debugging function, check for merge conflict tags and framework coding standard in files that are staged to commit. If any case fails then in the script we have to throw an error that is ‘exit 1’. Otherwise just do ‘exit 0’, which means success.

Example

Here, I have created a git pre commit hook example script specifically for Drupal. You can go through the code here: manoj-apare/pre-commit. First, we have to check these standards only on staged files and avoid deleted files, using command ‘git diff-index --diff-filter=ACMRT --cached --name-only HEAD --’. In rest of the article, I will explain what all checks have been covered for these list of files in the script and how.

Syntax check

For checking Syntax, you can PHP linter for compilation errors that is using command ‘php -l’. To run php linter check, we can filter out only php files ‘git diff-index --diff-filter=ACMRT --cached --name-only HEAD -- | egrep '\.php$|\.inc$|\.module|\.theme$'’.

Check for debugging functions

For checking debugging function, we can use grep tool ‘git diff --cached $FILE | egrep -x "$pattern"’. Where $FILE is filename and $pattern is regular expression pattern for debugging functions for example ‘^\+(.*)?var_dump(.*)?’.

Merge conflict marker check

Merge conflict marker can be checked on all files staged to commit using egrep pattern ‘egrep -in "(<<<<|====|>>>>)+.*(\n)?" $FILE’.

Coding standard check

Using phpcs (PHP codesniffer), we can check for coding standards ‘phpcs --standard=Drupal’. No need to check coding standards for some files format like images and fonts. For this, we can filter out staged files with extensions ‘php,module,inc,install,test,profile,theme,js,css,info,txt’.

See the screenshot below for an example of the coding standard check.
 

Git precommit hook

Finally, using git pre-commit hook we can make sure that we are pushing clean code. I hope this blog will help you out to check coding standards, syntax errors and debugging functions. Moreover, it will also assist you in reducing the number of failing automated tests in CI.

 

How to Create Form Table with pagination in Drupal 8

There are scenarios, where you will have a lot of users. In such an instance , if we display all the users in single page, it will mess with the user experience, to scroll through such a long list. By using Drupal pagination we can display the configured number of users in the single page.

In one of the previous blogs, we learnt how to create a Drupal table form, in this blog we will learn about creating the form table with Drupal pagination. When completed and configured with 10 users, the form can look like the below image.

Table Form with pagination  d8.png

Follow the below steps to create a configured user list with Drupal pagination

Step 1:

Get the data:

The first thing we need to do is to get the data which we will use in our table. This will be entirely dependent on what data it is that you want to show. The table shown above is displaying user info from the database. In this case, by using drupal db_select I’m fetching user detail and creating the array

    As you can see, fetching rows data from the database and putting them in the array format

Step 2:

Build the header The next thing we need to do is put together an associative (keyed) array defining the header of the table. The keys here are important as we will be using them later in this blog. The table we are building here has four cells in the header - one for the checkbox column, one for userid, one for username and another for email. However, we can ignore the cell for the checkbox column, as Drupal will take care of this for us later. As such, we can build our header as follows:

Step 3:

Build the data

Next, we need to build the array that will contain the data of the table. Each element in the array will correspond to one row in the HTML table we are creating. Each element of the array will be given a unique ID. This will be the value of the checkbox when the form is submitted (if selected). In this case, we want to get the UID of the user, so each row will be keyed with the UID of the user. We then, will key the cells of the table with the keys we used for the header.

Step 4:

Form Table

So now we have built a header ($header), and the rows of the table ($options). Create a simple drupal form and bring it all together. Drupal 8 has a nice little theme function that we will use for this, theme_tableselect(). theme_tableselect() takes the data, turns it into a table, adds a checkbox to each row, and adds a 'select all' checkbox to the header. Handy! So let’s look at how to tie this all together:   

That's it. This is a simple table form with the list of user from the database with drupal pagination.

How to manipulate Grid format view using draggable Views Module in Drupal 7

Draggable grid view makes views to be altered and rearranged as drag and drop. This is achieved by using javascript which allows drag and drop on HTML tables. In this blog, I will discuss about an instance where I used the Views Module to manipulate the grid format in Drupal 7.

The process of reordering the views can be done with the help of Drupal draggable  views module. With the help of the module we can easily re-order the table format, but if we want to reorder the  grid format, it requires some modification in the views that is created. In this blog I will be explaining about Drupal grid view which is the view that is visible for the user. 

You can download and install the module using drush commands drush dl draggableviews -y and then drush en draggableviews -y

After downloading and installing the module, the setup for the draggable views module is completed. 

Creating View:

We have to create 2 views , in order to create a re-orderable grid format view. In the first view we will create a view for the table format. It is the format generated when the module is installed then we can create another view of grid format(any format also possible).
To create a view  for the above process of table format, please follow the following  steps

  • Go to the link  admin/structure/views/add and create a page view of particular content type
  • Save the view and continue to add the format and field section in the view
  • In the format section please select the table format and  leave the settings options for the default values

Tableformat

 

  • In the field section add the following fields title, image( please add the field of  a particular content type you want to re-order, I have chosen image field to re-order) and Draggableviews: Content
  • Some configuration should be done for the Draggableviews: Content , please click on it and follow the uploaded image

Draggableconfiguration

  • Now we have to add a sort criteria , the sort criteria field will be updated with Draggableviews: Weight (asc). It can be ascending or descending based on the requirement. Now we have to set some configuration for the field, so please follow the image for the configuration

Sorting draggableviews

  • Save the view, now we are able to reorder the table format view.

Now we should create a view for the grid format mode. Creating Grid format mode view is similar to table format view. Please follow the below steps to create a view for that.

  • Go to the link  admin/structure/views/add and create a page view of particular content type
  • Save the view and continue to add the format and field section in the view
  • In the format section please select the grid format and  leave the settings options for the default values
  • In the field section add the following fields title, image( please add the field of  a particular content type you want to re-order, I have chosen image field to re-order) 
  • Now we have to add a sort criteria , the sort criteria field will be updated with Draggableviews: Weight (asc). It can be ascending or descending based on the requirement. Now we have to set some configuration for the field, so please follow the image for the configuration.

Gridsorting

In the image there is a field called Display Sort as, we have to set table formatted view name because, this view (grid formatted) will be sort based on the previous view (Table formatted view). Save the view, now you will be able to control the grid formatted display in any order.

After saving the view place the link in menu to see the operation.

  • Go to admin/structure/menu/manage/main-menu, to place the menu, I have choosen main menu the user can choose any menu, for placing the menu links.

Output:
The output has some procedures in displaying the view in any order. I will be describing with the help of image for the output. The Drupal drag and drop facility can be achieved for the users using Drupal draggableviews module. 

Grid formatted output

In the image there is quick edit menu button, if you click on that you will get two options 

  • Edit view
  • Order View

We have to click on order view , to change the order of the view displayed in the image.

order viewbutton

If we click on the order view it will be redirected to the view of table formatted, here we will change  the order of the view, it is a Drupal drag and drop format where the user can change the order of the items, and if order is changed and updated it will be affected in the Drupal grid view format.

Table formattedoutput

Now the order in the view is  E->B-> C-> D-> A in both the images, we can bring the order to A->B-> C-> D-> E , by altering the order in table formatted view.

Reordered image as per the above condition

output

In the end, now we are able to re order the video of grid format using the draggable views module but the above method can be done only by the admin who has privileges.

 

How to Setup Virtual Host in Windows 7 with XAMPP server

As a Developer, I would love to be called a “full-stack” Developer, whose job is not limited only to clean code & bug-free delivery, but also responsible to provide infrastructure, database, back-end code, front-end code and project management ;). I’m sure you won’t be interested in client call and daily stand up call, but this is a part of our work which helps in a successful product delivery as well as client satisfaction. 

Recently, I have moved on from Linux to Windows. You can understand a pain of a Developer when it comes to change your machine from hands-on machine to all new environment machine. It’s all new world with reinstallation of supported tools, drivers, applications that suit to your machine. 

As a Drupal Developer, I do deal with web servers. In this tutorial, I am going to share something that everybody would like to read about and i.e. “Virtual Host with XAMPP”. You must be aware of XAMPP before this tutorial also. XAMPP is a cross platform open-source web server bundle that consists of Apache, PHP, MySQL, & Perl. Anyone, who is new to the development or heard rarely about XAMPP, can visit https://www.apachefriends.org/index.html and download supported version for your machine. 

Why do we need to set up Virtual host ?

Setting up a virtual host allows you to use an alias name for your localhost. We can setup multiple vhost as per our need so that each local website can be accessible through specific name. Virtual address means IP-based, you can use different IP or different name for each IP’s. In other words, let’s say your site resides in "localhost/site1" and you want to load all the assets. There is always an issue when we follow traditional step like creating a folder inside "..\xampp\htdocs\site1". This is the place where we used to place our hosting site in Windows, and always get an issue when they want to fetch any file resides in those directory. In this case, URL becomes "http://localhost:8012/site1/sites/default/files/image.jpg". Due to an invalid path, files become inaccessible and as a result they won’t get loaded in the page.

Using Vhost, you can load from the root of your document without any movement of your site files.

There is nothing wrong on setting up Vhost in your local machine. Using this, you can also set up multi-site that uses wildcard DNS with sub-domain name. 

What I am running on:
I am running latest version of Xampp server with Windows 7 32-bit operating system. XAMPP having Apache 2.4.25, PHP 7.1.4, MySQL 5.0.12

How can we achieve:
Here we need to deal with three important files
1.    Host file
2.    Httpd.conf file
3.    Httpd-vhosts.conf file

Step 1: Let me start with httpd.conf file, which is apache configuration file. By default httpd-vhosts.conf becomes comment out in Ubuntu as it doesn’t uses. But in Windows, it uses vhost file, so we need to tell apache to include vhost file. If you find codes like below, then remove the comment (#) and save the file.
 

# Virtual hosts
#Include conf/extra/httpd-vhosts.conf

To 

# Virtual hosts
Include conf/extra/httpd-vhosts.conf

Location: C:\xampp\apache\conf\httpd.conf

Step 2: Create a virtualhost file. 
To create a virtualhost for your website, you need to push your code to the httpd-vhosts.conf file.


          ServerAdmin webmaster@localhost.com
         DocumentRoot "C:/xampp/htdocs"
         ServerName localhost

As you can find in the above code, I have included DocumentRoot and ServerName inside the virtual-host tag. Unlike the major tag, there are many other tags available. And you can use them as per your requirement.


    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot "C:/xampp/htdocs/dummy-host.example.com"
    ServerName dummy-host.example.com
    ServerAlias www. dummy-host.example.com
    ErrorLog "logs/dummy-host.example.com-error.log"
    CustomLog "logs/dummy-host.example.com-access.log" common

As you can see in the above code, we have ServerAdmin, DocumentRoot, ServerName, ServerAlias, ErrorLog, CustomLog. 

ServerAdmin:
Description:    Email address that the server includes in error messages sent to the client
Syntax:    ServerAdmin email-address|URL

ServerAlias:
Description:    Alternate names for a host used when matching requests to name-virtual hosts
Syntax:     ServerAlias hostname [hostname] ...

ServerName:
Description:    Hostname and port that the server uses to identify itself
Syntax:    ServerName [scheme://]domain-name|ip-address[:port]

DocumentRoot:
Description:    Directory that forms the main document tree visible from the web
Syntax:    DocumentRoot directory-path Location: C:\xampp\apache\conf\extra\ httpd-vhosts.conf

Below is my machine code:


    ServerAdmin webmaster@xai.com
    DocumentRoot "C:/xampp/htdocs/site1"
    ServerName site1
    ServerAlias site1
    
             Order allow,deny
        Allow from all
   

In a similar way, you can add many virtualhost for your local web directory. In my case, port no is 8012. Please do change accordingly.


    ServerAdmin webmaster@site1.com
    DocumentRoot "C:/xampp/htdocs/site1"
    ServerName site1
    ServerAlias site1



    ServerAdmin webmaster@site2.com
    DocumentRoot "C:/xampp/htdocs/site2"
    ServerName site2
    ServerAlias site2



    ServerAdmin webmaster@site3.com
    DocumentRoot "C:/xampp/htdocs/site3"
    ServerName site3
    ServerAlias site3


 

Step 3: We are almost done. As we have made changes in httpd.conf and httpd-vhosts.conf files please save it. Now, it’s time to tell the browser how to handle your new servername. In Windows, host files located in C:\Windows\System32\drivers\etc\hosts 

127.0.0.1       localhost
127.0.0.1       site1.local
127.0.0.1       site2.local
127.0.0.1       site3.local

………………….
 

vhost url browser

 

Like above, you can add as many as you create a new mapping for your local website.
Now, Restart your Apache and visit the site using URL. "http://site1:8012" , "http://site2:8012"  "http://site3:8012"

Related

Drupal 8 installation in Windows with XAMPP

Create Apache2 Virtual Host

Valuebound’s Awesome Team Outing at Woods Resort, Bangalore

It was a fine Saturday morning when we Valuebound started for Woods Resort, Bangalore for team outing. Soon after reaching the Resort, we were welcomed with great energy and delicious south Indian breakfast by Resort staff. During our breakfast, we met Anthony Raj and Roopa Karthi from event planning firm, Ice Bucket Events.

Rum Pom Pom, Guli Guli Guli, Olla la la la layo” - so you must be thinking what it is? Well, this is an African Tribal song, and we danced on this which acted as an icebreaker. The very first fun-filled activity for warm up.

With this, the list of activities started with forming three different units, named on American science fiction characters - Iron Man, Hulk and Wonder Woman. The leader of the team has to pick individuals based on three criteria - strength, beauty and intelligence. And it didn’t stop there, nominated candidates had to perform the given tasks. This activity was focussed on how we should cope up with the available resources in an organization.

Well, there were a number of activities throughout the day, however, it ended with dance on African tribal music, where each of us had to perform a unique step. The last activity had a strong, reminding every individual is different and able to solve the problem in their own unique way. 

Here is the list of quick snaps

A healthy discussion can be solution for everything. While a few giving candid pose.
A healthy discussion can be solution for everything. While a few giving candid pose.

 

You are “busted”. A mind boggling shooting game to check your reflex action.
You are “busted”. A mind boggling shooting game to check your reflex action.

 

Check your back and row the boat. A game of perseverance inspired from Kerala’s boat racing.
Check your back and row the boat. A game of perseverance inspired from Kerala’s boat racing.

 

Valuebound’s team performing Masai dance, showing their strength and stamina.
Valuebound’s team performing Masai dance, showing their strength and stamina.

 

The tiring, cumbersome physical activities ended with the dance on African tribal songs, which is known for increasing self-confidence and problem-solving skills. The activities were followed by delicious lunch buffet. And yes! We ended up in the swimming pool to relax, and after that rain dance, discotheque and finally hi tea. Below you can find a few glimpse of pool and discotheque too.

Being photogenic while giving cheesy pose has its own relevance. A quick snap with Ice Bucket Events team.
Being photogenic while giving cheesy pose has its own relevance. A quick snap with Ice Bucket Events team.

 

Well a picture speaks a thousand words. Valuebound’s team overwhelmed with water sports.
Well a picture speaks a thousand words. Valuebound’s team overwhelmed with water sports.

 

A beautiful art form to shut out all the tensions of your life.
A beautiful art form to shut out all the tensions of your life.

 

A moment to cherish. Goodbye! Woods Resort.
A moment to cherish. Goodbye! Woods Resort.

 

Not to mention, going for a team outing is the best thing to have some fun and a great way to relax and chill out from a regular life. It also gives new joinees an opportunity to know their colleagues outside of the office. And we are all set for the next trip.

 

 

Why relationship building is the key to successful marketing?

Cultivating relationships has been always an important part of sales and marketing, and it will always be. Attracting a stranger, converting them into a lead and providing solutions to their pain problem are the significant part of a marketing strategy.

Much has been talked from the developer’s perspective. Here in this blog post, I will talk about relationship building, why it is important and how it is applicable in an IT company? Apart from that, I will also discuss on ‘Why and How’ of Marketing based on Relationship Building.  

Relationships are still the driving force for how professional get the jobs they want and how the sales representatives outperform the rest of their team. These relationships are not built in a day or two. They require good professional networking.

This blog will focus on different agendas of relationship building or relationship marketing, which include Why, How and Challenges need to be tackled.

According to an article published by Forbes, a business is only as good as the clients it serves, and no business gets far after losing the clients it has.

Research shows that even with the best products and business practices, you still need strong relationships to succeed in this marketplace. Respect is at the core of building business relationships, management consulting firm Leading Insight said.

Sticking to the deadline is of utmost importance as it shows the value. At the same time, we need to grow in order to attract more and more customers.

Irrespective of whether we have prominent services in the world. At the end of the day, it all boils down to relationship building. So it is not just about an organisation or a brand. People by people first. 

Why we need to build relationship with clients?

People work with individuals who they like. So of course our objective as a business is to improve the life of a customer. The idea here is to tell how important relationship building is and how you can adopt it in your day-to-day life.

Relationships are not built overnight, it takes time to nurture. Strong, enduring client relationships are the lifeblood of the most organization. Understanding what your customers like, dislike or care help serving the business. As a solution provider, we also need to think from customers perspective in order to better understand “what they need?”

So, how can we create an enduring, institutionalized customer relationship? 

The answer to this question lies in what Andrew Sobel calls it Northeast Quadrant. In this space, first, an individual professional managing the relationship evolves his or her position from an Expert-for-Hire to a Trusted Advisor. 

Second, the company should develop its relationship from a narrow one based on few services to a broad one founded on multiple relationships. Third, as Vendor, the entity is responsible to broaden the relationship and develop a significant revenue from the client.

Lastly, becoming a Trusted Partner is an ultimate goal in order to be a trusted advisor to your customer and to deliver outstanding results. As a Trusted Partner, you lead your customer’s agenda.

client matrix
Credit: Andrew Sobel

 

What are the ingredients of building a good strong relationship?

The basic ingredients for building a healthy relationship with clients are trust, respect, mindfulness, communication and right approach.

I am sure you will be thinking, how does customer feel that you are one among them or part of their team? It happens only by communicating prospective customers on a regular basis. For this, we need to get to the right person so that an organisation get more and more customer.

It is our responsibility to make sure that communication part is taking place properly as well as how we can collaborate with the customers, listen to them and take the regular feedback.

Here comes the next, what are the strategies to build trusted client partnerships?

  • Strategy one: To become an agenda setter
  • Strategy two: To develop relationship capital
  • Strategy three: To engage new customers 
  • Strategy four: To institutionalize client relationships
  • Strategy five: To add multiple layers of value
  • Strategy six: To target the right customers
  • Strategy seven: To build a client leadership pipeline
  • Strategy eight: To promote partnership
  • Strategy nine: To listen your clients
  • Strategy ten: To create a unique client experience
trusted client partnership
Credit: Andrew Sobel

Finally, what are the challenges that hinders building trusted client partnership?

We presume, meeting the deadline that means delivering the product on estimated time helps in building trusted client partnership. Yes, that’s right!! However, at the same time, you need to accept your customer in terms of culture. 

It's always good to clear the doubts with the clients as well as share minutes of meeting to make sure you are not missing anything. While sticking to the deadline plays a significant role. Always remember that business is all about Relationships, Relationships, Relationships! It takes a long-term commitment to earn success.

People buy People first! Each one of us can make a difference….

Below given is a presentation on how to build client relationship through marketing.

7 Tips : Dev testing Best Practices

At Valuebound, Dev Testing is done to ensure that a product or service of a software is built and delivered as per the client requirements with maintained standards. It provides our team an overview of the risks of implementing a new software and checking it to determine if it is fit for use.

We do dev testing to execute software components in conditions with near or equal standards for deployment. This indicates that the developed application

  • Is built according to the requirements of the design

  • Passes all the test cases

  • Executes the functionality positively within the stipulated time frame

  • Is executable under different intended environments intended environments, and

  • Meets the standards of responses as needed

To deliver the best of services and applications, we follow these points

  1. Pair programming - Knowledge increases with sharing. Involve people while you code or for some people maybe after you code, that way you not only share the knowledge, you also get to check commonly missed errors, a comma or semicolon at the wrong place put by mistake can be deadly to find. Active participation and feedback will help to improve code quality.

  2. Involve QA from the beginning - Do not wait until the last minute to involve the testing team. Start at the beginning so that the testing team is aware of the functionalities and requirements. A client would not want to go through buggy codes and it is sensible to involve dev testing for all levels of SDLC. Involving QA enables the testing team to design tests and modeling. This will prevent bugs and hold on to the quality during the whole project.

  3. Automate - Avoid using tests which are not automated. Manual testing on several platforms wastes a lot of time. Cross platform testing happens seamlessly. Automation tools mostly have integrated reporting system with it which further reduces time.

  4. Prioritize bug fixes - When a user is on your website, the last thing you would want is for the person to come across bugs in the functionalities. DO NOT leave them for the last, invest time and resources to address issues and complete bug fixes as soon as you come across.

  5. Defined recovery - Make sure there are ways to retrace back your steps.

  6. Maintain Documentation - For developers reliable documentation is is absolutely necessary. Documentation keeps tracks of application and its improvements on the product. Documentation serves as an aid to development, maintenance, and awareness to others. Proper documentation will make information easily accessible, help in troubleshooting, installation, and deployment.

  7. Think Environments - Testing environments are software setups designed for executing an application in various test cases with different configurations, browsers, and models. So as to ensure it executes smoothly and bug-free for all kinds of environment. You must have visited a website that has a button that works in Windows 7 but not 8. Testing environments avoid exactly that.

For every app that is tested and deployment, a happy user commends the product, growing business for clients and enabling the developer with smarter work. It makes easy to track developments, revisions and create world class products.

Valuebound is excited to sponsor Drupal Camp Pune 2017

We are proud to announce that Valuebound is sponsoring and participating in Drupal Camp Pune to be held on 29th and 30th of July. We also have Rakesh - one of our senior most Drupalers as featured speakers at the Camp.

This year's Camp intends to cater to a wider audience. The idea is to bring together a diverse group of Drupal lovers and to-be Drupalers and showcase the community, its ideas and the people who make this community so wonderful, not to mention the learnings it would entail.

Valuebound has actively sponsored and participated in a host of camps worldwide and Being at the Pune DrupalCamp, is a great opportunity to connect with the community and the developers in general. Contributing to Drupal is fundamental to the transformation and innovation of an organization and individual today and into the future, as the Internet gains traction as the primary source of information.

Drupal is backed by one of the world's strongest community of open source developers and enthusiasts, Drupal is supported and contributed to by a wide range of organizations and individuals. It is a CMS that focuses on delivering the best of digital experiences and content to the right audience at the right time. It innovates some of the leading organizations like NBC universal, Tesla, and the US government to power web applications for content creators, marketers and admins for easy workflow management, commercial experience and seamless digital experience across all channels. The Drupal community also organizes Drupal Camps and events globally throughout the year to open up opportunities for Drupal users to network and build the community for the continuous development of individuals and platform in turn.

Valuebound has consistently been one of the top Drupal contributors in the world and in India, building responsive and intuitive design with inputs in workflow management and insights for content management.

How to add a Product Programmatically to Drupal Commerce Cart

In last two blog post we discussed the basics of getting started with Drupal Commerce and the steps of e-commerce products creation. As we move forward with our learnings, we will write about how we dealt with those. 

There is Business logic which demands few things out of the box where we create custom modules to aid a process. I came across a situation where we had to use Drupal Commerce module but the product was coming from the content type. Even though we had to import the product as commerce product still we couldn’t use them directly. Here we had to add the product to the cart programmatically where I could only get product id from the URL and that particular product needs to be added to the cart and commerce flow needs to be implemented. 

Showing below are the steps that I have followed to add the product to Drupal Commerce Cart Programmatically. I have Created a Custom Modules ‘my_cart’ to demonstrate the above. 

For the below code to work, we have a dependency of using Drupal commerce modules and its dependent modules.

 

Product to Cart

 

 There you have it, it is nice and simple way to add the product to the Drupal commerce cart.

Schedule Automated Tasks in Drupal with Cron

Cron, A daemon/background process that runs at periodic intervals of time. It can be run periodically at pre-decided times and intervals. To describe in real-time, I have met with a case where I have to fetch the content from a site, where new content might be created everyday and create it on my site. To handle this, I have created a cron job, configured it to run every day at a specific time let’s say at 05.00 AM. So whenever the cron runs, I have written a script to fetch the content that is created on that day and creating on my site. All this is achieved using the cron in Drupal.

Cron is a utility which executes commands at set intervals known as "cron jobs".
According to drupal.org “A "cron job" is a time-triggered action that is usually (and most efficiently) performed by your website's hosting server, but can also be configured by a remote service or even from your own desktop”.

Related: How to Handle Intensive Tasks on Queue With Drupal Queue API

Where can we use?

It can be used for Importing files, sending emails, Publishing the code, Fetching the content from an external site every day, etc.

How can this be implemented in D8?

Drupal 8 provides an automated Cron. This is a built-in tool that is time-based task scheduler. The name itself indicates Automated which means no Manual involvement is required other than the initial setup. By default, this cron is set to run every 3 hours. We can change it accordingly for every hour, daily basis, weekly basis as per the requirement. We can even alter the settings form and add our own periodic intervals.

How can we use this Drupal cron to run the custom periodic task?

hook_cron: This hook is triggered whenever the Drupal cron runs. So, we can define our task inside this. For example, I want to check if there are any unpublished nodes, I want to publish them each time when the cron runs.

Now how does execution happen?

  • Execute cron manually from the Drupal admin interface.

  • Using Drush command:

Drush cron

Limitations:

  1. In case we have multiple modules implementing hook_cron, these run at the same time either alphabetically or as per the module weight. This adds more weight to a page request at one point in time.

  2. If one cron results in an error, this stops the cron running which will not process the remaining ones until it is solved. Also, its tough to find out who is the culprit.

  3. If we want to optimize the cron run time, we should analyze which cron run took more time.

To overcome all these limitations, Drupal provides us with modules like Super cron, Elysia cron, Ultimate cron etc.. All these modules are one or the same with more added features. How does this help?

  1. No one by one execution, Its parallel now. So, even if there is an error with one cron task, the other executes independently of each other.

  2. Each can have a separate configuration. so I can say run my cron job at every 1 hour, cron job B at every 2 hrs.

  3. Each has separate logs.

  4. Supports Drupal Queue

Out of all these modules we have, Ultimate cron is available now in D8. This has more features comparatively.

Ultimate Cron:

Ultimate Cron

Misconception: Assume, I have a case where my main cron is set to run for every 3 hours, and my custom cron job task is set to run every one minute. In this case, my cron job doesn’t actually run every one minute. Yes, it’s true. How this actually works is: When any user hits our site, it takes the current timestamp and the last cron run timestamp. If the difference is greater than the cron interval time, our cron job is only triggered then.

How can we make use of ultimate cron for our custom job?

  1. Define a yml for the ultimate cron job in the install folder.

2. Define Callback.

3. Install the module.

4. Go to Cron in UI, click on Discover jobs. This shows the newly created cron job.

Cron with Batch:

We know there are cases where we want to do operations on a large amount of data. For this, we prefer Batch process so that it happens in bulk instead of one by one. For example queue. When we try to update let’s say, 50k of data with almost 20 fields each, it may result in a time out. So we want this to happen in the background process and I want to add content in chunks lets say, 5k of content each time in order to reduce the load. We can use cron with batch.

  1. Define .yml

2. Define Callback

3.Define QueueWorker

Related: Batch Process in Drupal 8

Ultimate cron also facilitates with an option "Override cron Queue processing". This option creates a cron job, automatically for a queue worker.

Limitations:

  • The site should be active. Yes! if the cron is set for 1 hr, it is not compulsory that it keeps running for every 1 hr. it’s a misconception. the cron only runs if there is any user visiting. Which means the site should be active. let’s say if the cron is set for every 3 hrs, and no user visited your site for a week, then the cron doesn’t get triggered.

  • Cron Processing still adds to page request. Whenever the crown runs, it adds load to the page request.

External crons:

These are the ones that can be set up on external sites. We have Easy Cron, Cron Less etc.  So, whether or not there is a user visit, the cron still executes.

To improve the site performance, we can disable the automated cron in ur site. This stops all the cron jobs even that are unnecessarily/unknowingly running on our site. Even we disable the cron, our cron job can still be executed if we are making use of external crons.

To disable the automated cron:

Set the "Run cron every" value to "Never"

                     (OR)

Add the following line to your settings.php:(so that no user can enable it).

$config['automated_cron.settings']['interval'] = 0;

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