Extend existing field widgets in Drupal 8 application using annotation plugin

Have you ever wondered how the text or email or entity reference field is extended in Drupal 8? Or how to create a custom field/widget/formatter so that it can match with the rest of fields in your Drupal application? This blog will cover everything required to extend existing field widgets in Drupal 8 using annotation plugin. 

Many developers, who recently started working on Drupal 8, may not be aware of an entire process so let’s take a closer look to everything step-by-step. Key comparisons between Drupal 7 and Drupal 8, what is an annotation, why annotation and sample use case from an Inline Entity Form step-by-step. After completing this post, you will be able to extend the field with your own methods/functions without disturbing contributed module code.

Note: The below-mentioned functions are used to access properties of available widgets, which are moved to methods on the Widget Plugin Manager.
Comparisons

In Drupal 7

  • hook_field_widget_info() is replaced by annotation-based plugin 
  • hook_field_widget_settings_form(), hook_field_widget_form(), hook_field_widget_error() : replaced by Widget Interface methods

In Drupal 8

  • hook_Info is replaced by annotation-based-plugin
  • public function settings Form(array $form, array &$form_state)
  • public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, array &$form_state)
  • public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, array &$form_state)

Let’s take a brief look at Annotations as it plays a significant role in extending FieldWidgets.

Annotations are one of the new concepts in Drupal 8, which are written as  PHP code comments above a class or function. Annotations contain metadata about the function or class.

Note: In Drupal, we have an option to add metadata about the functions inside the comment block so that it can automatically take annotations when Field Widgets rendered on the page. It will help in avoiding multiple files to declare the metadata information.

Why Annotations?

The annotation meta-data lives in the same file and is an integral part of the class that implements the plugin. 

This makes it easier to find and to create a new custom plugin by simply copying an existing one.

In addition, Implementation used by Drupal to parse the annotation simply tokenizes the text of the file without including it as a PHP file, so memory use is minimized.

The annotations syntax comes from the Doctrine project, which is nothing but the docblock annotations.

Sample use case from an Inline Entity Form in Drupal 8

Real Entity (node) has been removed from backend when removing contacts field values. Contacts field is an Entity reference field with unlimited cardinality.

By showing this contact with Inline Entity Form - Complex Field Widgets on node edit page.

To avoid this, we need to extend the FieldWidget from an inline entity form - complex. Have a look how to do it programmatically.

Note: Based on the settings, we can control the original entity deletion from the backend. For this, we can use public function settingsForm(array $form, array &$form_state) to add checkbox “Delete referenced node on remove”.

Create a module folder extend_inline_entity_form

Folder Structure: src/Plugin/Field/FieldWidget/ExtendedInlineEntityForm.php

After enabling the module, you can find a similar interface. Here you need to disable “Delete reference node on remove” checkbox to prevent the original node deletion on the backend. Check out the screenshot below for an example.

Field Widgets

Extending an inline entity form - complex - is nothing, but preventing the deletion of an original node from backend when we remove the entity. With the above-mentioned code, we can unset the widget_state[‘delete’] to stop the deletion of an original node from the backend.

For the above code to work, we need to select the “Delete reference node on remove” checkbox to extend an inline entity form - complex. It can be configurable now! We can add this as a patch to drupal.org or we can contribute this as a sub-module to an inline entity form in Drupal. 

That’s it. Hope you can now extend FieldWidgets using an Annotation plugin. If you have any suggestions or queries, please comment down.

Below given is a presentation on extending Field Widgets in Drupal 8.
 

Step-by-step guide to Foundation framework to develop responsive web applications

Creating responsive websites have always remained a challenge for many even I faced similar difficulties in the beginning. Recently, our team came across a situation where we had to design a responsive and beautiful website in Drupal 8 for a media and publishing firm. In order to create such an amazing site, we came up with an idea to use Foundation Framework and yes! it worked.

I have written this blog to help anyone having difficulty in understanding the Foundation framework to develop responsive websites as it is a rising market demand. My idea is that this article will be a "living laboratory" to help you in understanding Foundation from the scratch. The post comprises an intro of Foundation, its features, comparison with Bootstrap, getting started with Foundation. At the end, you can also check out the list of prominent brands using this framework. You may also like to check out our previous blog “An overview of Foundation: A Frontend Framework for Responsive Websites.”

First things first, an Introduction

Foundation is an open source front-end framework that helps in designing responsive websites, apps, and emails. It provides a responsive grid, HTML and CSS UI components, templates, and code snippets, forms, buttons, navigation, other interface components and optional JavaScript extensions to build a responsive site.

Features 

Foundation has been designed for and tested on various browsers and gadgets. The open source framework is a mobile-first that give developers best practices for rapid development. Other features of Foundation - it is consist of 12 column grid system, supports stylized CSS components and RTL (right to left) direction format and compatible with several browsers.

12-Column Grid System:

grid

Credit: Codementor

Media Queries:  

Foundation has three core Breakpoints.

Small  Any Screen up to 639 px.
/* Small only */
@media screen and (max-width: 39.9375em) {...}

Medium Any Screen from 640 px or Wider.
/* Medium only */
@media screen and (min-width: 40em) and (max-width: 63.9375em) {...}

Large Any Screen from 1024 px or Wider.
    /* Large and up */
@media screen and (min-width: 64em) {...}

Compatibility:

In addition to Android browsers, Foundation also supports all the latest versions of Chrome, Firefox, Safari, Opera and Internet Explorer. 


compatability

Credit: Codementor

Widgets:

Below are some widgets & JavaScript features developed in Foundation that Bootstrap does not support.

widgets

Credit: Codementor

Let’s check out some of the differences between Bootstrap and Foundation:

Well, there are many differences and similarities between Bootstrap and Foundation. The main similarity is that they are both great front-end frameworks that can be used to build an awesome application and website.

Comparison

Bootstrap Classes

Foundation Classes
col-xs-*small-*
col-sm-*medium-*
col-md-*large-*
col-lg-* 

CSS3 Preprocessors

CSS3 Preprocessors
LESSSASS(SCSS)
SASS(SCSS) 

RTL (right to left) Format

RTL (right to left) Format
Doesn’t support RTL formatSupports RTL format

 

Note: Bootstrap supports both LESS AND SASS (SCSS) Preprocessors, but Foundation supports only SASS (SCSS). Here * represents a number, valid up to 12.

Getting Started with Foundation:

Well, there are many ways to install Foundation, but here I will be discussing two ways: First by CSS and second by using the terminal.

If you are just getting started with CSS then you can download Foundation. Customize it and choose the features you want to have on your website. 

While getting started, you can find a couple of options like Downloading complete Foundation and Download customized Foundation. Select as per your requirement.

After downloading Foundation, your folder structure would look like this. See the screenshot below.

structure

  • app.css  is the custom css file which we can add on our own css
  • foundation.css is the default css implemented by Foundation
  • foundation.min.css  is the minified css 
  • jquery.js is required to provide the Responsive functionality to the website. You just need to have JQuery version 1.10 or higher on your page before the foundation.js library.
  • what-input.js is used to track the current input method. 
  • foundation.js  is used for utilizing core functionality.  
  • app.js  is the custom js file which we can add our js.
  • You need to specify all the above files in your HTML file.
  • You can also install Foundation CLI by using Terminal 
  • sudo npm install --global foundation-cli 
  • Once you've installed the CLI, use the new command to start making a new project:
  •     foundation new

See the screenshot below for an example of Websites designed with Foundation Framework.

sites

Credit: Codementor

Prominent brands using Foundation Framework:     

  1. PBS: Public Broadcasting Service
  2. National Geographic
  3. Washington Post
  4. Mozilla
  5. Cambridge University Press
  6. Official HTC Store (UK)
  7. National Geographic Education
  8. Burger Revolution

 

Using Foundation Framework, we can build responsive websites that will be both unique and beautiful. In this blog, we have explored the basics of Foundation Framework, its overview, features, companies using this framework to design responsive sites as well as how to install customized Foundation using terminal and CSS. This blog is intended to give you a brief intro of the framework and its comparison with Bootstrap. 

Foundation Framework helps in reducing the CSS and JS, so we recommend you to try multiple front-end frameworks to find out what works better for your current project. Based on your comments and suggestions, I plan to add to it, creating additional value. Or maybe it is perfect as-is!

 

An overview of JSON API: A text-based data exchange format

People develop APIs for a variety of reasons, such as to create a tool to facilitate internal processes or an external product for customers or to build a third party tool. And for such purpose JSON comes to the rescue. The open standard format JSON follows shared conventions that help in increasing productivity, take advantage of generalized tooling, and focus on the web applications. 

If you are a developer you must have noticed that there is very little information on the web regarding JSON API when compared to its usability. In this blog post, I will share an overview of JSON API. Let's try and understand what is JSON API? Its advantages over Core REST API, core concepts with working examples.

Note: JSON is an independent component, which can be used by any framework or technology. In our case, Drupal is using its service.

Let’s start with what is JSON API?

JSON or JavaScript Object Notation is an encoding scheme that is designed to eliminate the need for an ad-hoc code for each application to communicate with servers that communicate in a defined way. JSON API module exposes an implementation for data stores and data structures, such as entity types, bundles, and fields.

What are its advantages over Core REST API?

Well, there are lots of advantages, but to mention a few:

  • It reduces both the number of requests and the amount of data transmitted between clients and servers. 

  • Unlike core REST module, JSON API is Zero configuration Drupal module.

  • By enabling the JSON API module, you can immediately gain a full REST API for every type in your Drupal application.

  • JSON API inspects entity type and bundle to provide URLs to access each one of them using the standard HTTP methods, GET, POST, PATCH, and DELETE (we will discuss more on HTTP methods while talking about Document Structure).

  • JSON is not simply a format like JSON or HAL+JSON. The default format appears like:

                       `/jsonapi/{entity_type}/{bundle}/{uuid}?_format=api_json`

  • It also controls which HTTP methods should be used, what HTTP response codes should be returned under specific request, the format of the response body, and the link between resources.

Document Structure:

This section describes the structure of a JSON API document, which is identified by media type. Though the same media type is used for both request and response documents, certain aspects are only applicable to one or the other.

1. Every request/response body must be underneath a single JSON object.

2. data: the information specific to a resource or resources, must live within this top-level object under the data member.

3. type and id: JSON API derives  'type' property from the entity type machine name and bundle machine name.

Note: id in the JSON API are UUID (If we have the same site installed at different places, the nid for the same content mostly be different but UUID remains same on all environments.).

4. attributes and relationship: attributes store values specific to the underlying resource.  relationships represent values that are stored by an entity reference.

Request headers: 

Accept: application/vnd.api+json
Content-Type: application/vnd.api+json

Response Codes:

The JSON API module can respond with the following codes:

200 OK - All successful GET and PATCH requests

201 Created - All successful POST requests (response includes the newly created 
        resource).

204 No Content - All successful DELETE requests

HTTP Methods in Drupal: 

Hypertext Transfer Protocol (HTTP) enables communication between clients and servers. It also defines a set of request methods to perform a certain action for a given resource. In Drupal 8, JSON API supports GET, POST, PATCH and DELETE HTTP methods. 

1. Fetching resources (GET) 

A web request using GET method is made only to retrieve data from a given resource. It specifies different parameters in the URL of the request based on requirements. One can make web request either by using the web browser or any other HTTP client (e.g. Postman chrome app).

To fetch all contents of Article content type, URL should be: example.com/jsonapi/node/article
Sort articles (descending): example.com/jsonapi/node/article?sort=-nid 
Filter out first five contents:example.com/jsonapi/node/article/?page[limit]=5 

Similarly, we can add various filter parameter in the URL based on our requirement.

Note: JSON API lists 50 objects at a time including link to next.

GET-json api

2. Creating new resources (POST)

Submit data to a server to create a new content.

Prerequisites:

  • Make sure HTTP Basic Authentication Drupal core module is enabled on your site.
  • Following headers are required to get correct response:

                                           Accept: application/vnd.api+json
                                           Content-Type: application/vnd.api+json

  • Add basic authentication (credentials to your site)

                                           Authorization: Basic YXBpOmFwaQ==

To create a content named “Hello Article” and body, write the following code in HTTP message body:

URL: example.com/jsonapi/node/article

See the screenshot below for an example

POST-jsonapi

Check if the new content gets created from Drupal site (/admin/content).

3. Updating existing resources (PATCH)

PATCH method submits data to a server to update an existing content.

Prerequisites:

  • Make sure HTTP Basic Authentication Drupal core module is enabled on your site.
  • Following headers are required to get correct response:

                                        Accept: application/vnd.api+json
                                        Content-Type: application/vnd.api+json

  • Add basic authentication (credentials to your site )

                                       Authorization: Basic YXBpOmFwaQ==

To update an article’s title content, write following piece of code in HTTP message body:

URL: example.com/jsonapi/node/article/{{article_uuid}}

PATCH-jsonapi

Verify if the content gets updated in Drupal site(/admin/content).

4. Removing existing resources (DELETE)

DELETE method is used to request the server to delete a specific content.Simply run the following URL to delete any specific article content. 

URL: example.com/jsonapi/node/article/{{article_uuid}}

Prerequisites:

  • Make sure HTTP Basic Authentication Drupal core module is enabled on your site.
  • Following headers are required to get a correct response:

                                      Content-Type: application/vnd.api+json

  • Add basic authentication (credentials to your site )

                                      Authorization: Basic YXBpOmFwaQ==

DELETE-jsonapi

 

Check if the content gets deleted from the Drupal site (/admin/content).

Well, JSON is a way to store information in an organized, easy-to-access manner as it gives us a human-readable collection of data that we can access in a logical manner. Hope this blog will be helpful for you to understand and use JSON. If there is anything you would like to add or see further clarified, please let me know me in comments.

Below given is a presentation on JSON API.

References 

https://www.youtube.com/playlist?list=PLZOQ_ZMpYrZsyO-3IstImK1okrpfAjuMZ 
https://www.drupal.org/docs/8/modules/json-api/json-api 
https://nordicapis.com/3-methods-for-documenting-json-api-services/ 
http://www.json.org/
 

How to Handle Resource Intensive Tasks on Queue With Drupal Queue Worker/API

It's never too late to share something useful with mates. And in this blog, I am going to discuss Queue Worker/API and how to implement it in Drupal 8. After completing this blog cum tutorial you will find yourself at a moderate level of expertise in implementing Queue API.

A couple of months back, we had a situation in one of our project where we had to pull data from a centralized server and update that content to the site almost every day. In order to overcome this scenario, we started using cron, but faced a situation where we were missing few contents because of time out. After a little research and discussion, we (our team) decided to implement queue worker. And yes! It worked.

Let’s start with Queue API.

Queue API enables us to handle a number of tasks at a later stage that means we can insert a number of items in the queue and process them later. The items can be added to the queue by passing an arbitrary data object. And we can run Queue by manually using Drush commands or Cron. Cron is a background process that runs at periodic intervals of time. For an introduction to cron, you can check out our previous blog on “scheduling Automated Tasks in Drupal with Cron”.

So why should we use Queue Worker?

Queue Worker allows you to run queue with time limits. You can also individually queue the tasks at one time compared to Cron that run at the periodic interval of time. In comparison to cron, Queue is more efficient and can handle resource-intensive tasks. The API also allows you to revert the item back to queue if any failure occurs. Most importantly, you can run multiple queues without interrupting other work.

The very basic concept of Queue API is FIFO (First-In-First-Out).

Check out an example of the above-mentioned scenario.

Here we will create a Queue Worker that will fetch data from centralized repo using API and create an article on our existing site. This process will run automatically based on cron.

See the screenshot below for an example of the folder structure that will contain required files and their respective location:

Article_queue_folder_structure

Module Setup:

article_queue.info.yml

In Drupal 8, the menu system has been replaced by the routing system.

article_queue.routing.yml

ArticleSettingsForm.php

Create the Configuration form to store API link and their credentials. After entering Connector Site URL, Site User Name and Site Password, save the configuration.

ConfigForm

Let's see how we can use cron to add data to Queue.

In a hook_cron method, we will be defining a method to fetch data from API and adding to queue. 

First, create a QueueFactory object from the service container statically and use this object to instantiate a queue object of article_queue_processor.

Here we call create Item method to insert items in the queue. Once cron runs it will insert all items fetched from API in the process queue.

article_queue.module

In this example, we will be using ultimate cron for processing the cron. We need to set up we need to create a config file.

ultimate_cron.job.node_queue_worker.yml  

Need to place inside install folder. If the module is already enabled, we need to import this file using configuration management interface.

Now create a class to call processItem() that will process the queue.

ArticleQueueProcessor.php

In this method, we are going to define the processItem() method to create a node from the data received in API. 

Once cron run is completed, an article will be created on the site. 

To check this manually, we can navigate to “admin/config/system/cron/jobs”  and run the cron “Article Queue Worker”. After cron run navigate to “admin/config/system/queue-ui” and select “Task Worker: Node” and run batch process. Once the process is over your content will be created on the site.

That’s it!

See how easily you can deploy Queue Worker/API in Drupal to handle a number of resource intensive tasks at a later point of time. With Queue Worker, items can be added by passing an arbitrary data object. Also, using this API, you can easily manage your resource intensive tasks on your website. 

Hope you can now implement Queue Worker/API in Drupal. If you have any suggestions or queries please comment down let me try to answer.
 

Restricting access for anonymous users on a Drupal website running on Apache

Hello folks! Here is another blog that will help you to restrict anonymous or unwanted users entry on your web application when it is in development mode on the server. You will be wondering why did I come up with such an idea? And how it will help you out? This is what we will be discussing in this post. Quite a times we ignore to restrict anonymous entries due to some data integrity and that results in spoiling our site.

Let me tell you how? 

Recently, one of my friends has started working on his Drupal website from the scratch and he wants to stop the anonymous entries whether it's a new registration or anonymous view or comments as he is working on some serious stuff. Further, he doesn’t want to spoil the site from unknown users. And for this, he decided the restrict web application to an anonymous user. You may also like to check out our previous post where we have explained how to secure user’s private data from unauthorized access by enabling SSL on web server.

Note: It will be open up for generic users, who all are the part of the ongoing development with the help of Authentication Prompt.

Check out some of the ways that will help you to tackle the similar situation: 

  • To restrict registration - Don’t allow anonymous user registration

  • To restrict login - If you follow first

  • Anonymous Comment - Turn off comment system 

The above-mentioned ways are alternatives to prevent anonymous users from getting access to your site. When you limit access to your website, you need to allow site access only to those users who have correct admin credentials. And they are only allowed to grant the access. This can be accomplished using .htaccess & .htpasswd.
 
I guess you won’t be surprised of hearing these two names as you might have seen these residing in the root directory of your server.

.htaccess: A configuration file in '.htaccess' is used to run a web server like Apache. When a .htaccess file placed in the root directory of your website, it gets loaded through Apache, and then .htaccess file gets executed by Apache web server.

The .htaccess file is used to alter the configuration, enable or disable additional functionality and features of the Apache web server. Also, these files provide basic redirection, content password protection or image hotlink prevention. This method is called htaccess password protection or htaccess authentication.
 

htaccess location in root filder

 

Creating a htaccess file

You can create a .htaccess file by entering few lines of code that needs to be read by Apache. Further, to protect the site you need to write code that will be read by Apache before directing from the server to the end users.

AuthUserFile  full path of .htpasswd
AuthType Basic
AuthName "write some description here"
Require  valid-user

The AuthName parameter defines the title of the password entry box while login. Remember, here, the declaration is important.

The AuthType is a method used to authenticate the user. The common method is Basic, which is implemented by mod_auth_basic. The basic authentication sends credential from browser to server.

AuthUserFile: It is a full path of .htpasswd file.

Require: It provides authorization to set up the user, who is allowed to access the area on the server.

Note: We can give access only to specific users and all other users are supposed to be listed in .htpassword.

Only to specific user

require user  parameter in .htaccess for individual access

Below-mentioned source codes are from my local .htaccess that allows access to specific users

AuthUserFile C:\xampp\htdocs\.htpasswd
AuthType Basic
AuthName "My Secret Folder" 
require user xaiwant

All user listed in .htpasswd

require valid-user parameter in .htacess for all user access.

Following source codes are from my local .htpassword that give access to all users. 

xaiwant:$apr1$zx523D3t$VXU..vXqErSd1wOlSI9k41
want:$apr1$d7eWG8M.$PVnGYLZwuuzIXRXNxQ4Be0

With a password, the .htaccess file can protect your website, including all files in the folder and sub-folder too. Not to mention if you want to protect your website from unauthorized access, you have to place a .htaccess file in root folder.

AuthUserFile C:\xampp\htdocs.htpasswd\.htpasswd
AuthType Basic
AuthName "Drupal 7 Instance"
Require user xaiwant

 

.htpasswd: htpasswd file is used to store usernames and password for basic authentication of HTTP users. This file is called as Apache htpasswd aka Apache password file.

In case you find any difficulty while login to the prompt, then it must be htpasswd access issue (Read/Write) due to permission and same is likely to throw an error.
 
Resources available from Apache can be restricted to users by using the files created by htpasswd. Files managed by htpasswd may contain a mixture of different encoding types of passwords.

Creating a password file

Create a text file that store username and password separated by colon [:]. The password should be in encrypted form, which means you can utilize online web tools to generate them. Here I am sharing one of the URLs.

http://www.htaccesstools.com/htpasswd-generator/

Below is the encrypted credential of one of my local instance:

xaiwant:$apr1$zx523D3t$VXU..vXqErSd1wOlSI9k41

Copy and paste your encrypted credentials and then save the file. Place the folder out of your directory so that nobody can view the file. 

Similarly, you can also create a file name with your choice like xyz. It’s always suggested to change the filename so that it can’t be guessed by Hackers. FYI, Apache provides better file security in terms of web-based access to those files which starts with .ht. 

Still, if you want to know more then please visit http://www.apache.org/ or Google it for more valuable and authentic information.

To add password protection, you need to: 

  • Create a txt file .htpasswd on your server, which will store your username and password.

  • Create a special file, called .htaccess, in the folder you want to protect.
     

That's it! Now let's take a look at how to do each step.

Note: Don’t forget to Restart your server after making all the required changes.

Now hit the URL in the browser and you will get a prompt box asking for username and password. Enter the corrected credential and you are in.

Authentication Pop up

 

Note: You can access the folder n number of times on the server or on the local machine till your browser is open. Once you restart the browser, you will be asked for login credentials again with prompt box.

In case you haven’t been asked for credential then you need to check whether: 

  1. File path is correct or not.
  2. File is accessible or not. Related to permission.
  3. Entered credentials are correct or not.

There you have it! I guess this is the easiest and simplest way to set up the restriction on Drupal website that is running on Apache server. By using “.htaccess” and “.htpasswd”, you can easily limit your site from anonymous entries whether it’s a new registration or anonymous view or comments.

The goal of our blog is to bring you valuable information to help you grow your business. We hope you enjoy this post! We invite you to comment below or ask any questions you may have.
 

Managing Drupal 8 applications remotely using Drush aliases

Have you ever thought that your business needs to make sure that your web application has a quick release in order to sustain the long race. This sort of has become easy to manage by continuous development & continuous integration using Drush & Drush Aliases. Drupal web development is one such place where multiple command-line interface (CLI) tools are available to make developer’s life easy, and among them, the two important things are Drush and Drupal Console.

In this blog, we will take a brief look at Drush & Drush Aliases and how it can make developer’s tedious manual web development tasks easy by offering various commands to replace the manual steps. You may also like to check out our previous blog where we have discussed how to write the custom Drush Commands in Drupal 8.

First thing first, what is Drush?

Drush is a Command Line Shell Interface, which provides its own dictionary of commands to interact with Drupal modules/ themes/ profiles. For instance, If you want to enable the Drupal project (modules) on your website then all you need to do is execute the following command in your CLI.

Drush command

How to install Drush in Drupal 8?

The easiest way to install Drush on Drupal 8 instance is by using Composer. Just hit the below-mentioned command in your CLI and you are done with installation. Learn more about installing Drupal with drush on our previous blog.

composer command

 

What are Drush Aliases?

An ‘Alias’, in general, is nothing but a small representation/acronym for something bigger. In case of Drush, the ‘Aliases’ are a short form of Drush Commands. Quite often when we have to ssh on our remote servers to perform different operations, the process becomes a tedious task and even more tedious when we have multiple instances. This is where Drush Aliases comes to our rescue.

Drush

Here you have three instances “Dev > Stage > Production”, remember, all the three instances can be configured by Aliases so that Drush can perform its tasks on the remote server(s) from your local server.

Some of the common tasks can be ‘Database Sync’, ‘Files Sync’, ‘Cache Clearance’, ‘Module Operations’, ‘importing and exporting the configuration’ e.t.c.

How to set up local Aliases?

  1. Create an alias file in .drush folder of your home directory(~/.drush) to make Drush aliases (short commands) accessible from anywhere. Drush alias file must be named similar to the below convention.                                           

sitename command

 

Make sure your newly created alias file contains below snippet.

Similarly, you can create alias file for remote servers as well.

      2. The following snippet, when placed in your alias file, will automatically create aliases for all of your projects.

Note:  You can add $local_sites path and /docroot as per your local configuration.

If you are using Acquia and Pantheon as a remote server, you can follow the below-mentioned steps to set up the aliases on your local machine.

Acquia and Drush Aliases

  1. Sign in to the Acquia Cloud interface using your credentials.
  2. Click your name in the upper left corner and then click Edit profile.
  3. On the Profile page, click Credentials and then enter your Acquia password.
  4. Under Drush integration, click Download Drush aliases
  5. Extract the downloaded archive file into $HOME:  
  6. tar -C $HOME -xf $HOME/Downloads/mysite.tar.gz or you can place mysite.aliases.drushrc.php file into .drush folder manually.
  7. Now go to your terminal and run drush sa command to check aliases.

Pantheon and Drush Aliases

  1. Sign in to Pantheon dashboard using your account details.
  2. On the home page you will find Drush Aliases, click on it to download the file.
  3. Now you can place that file inside .drush folder.

Drush commands - A fast and easy-to-use command reference for Drush users.

  • $ drush @staging updatedb - This command is used to run pending updates on staging site.

  • $ drush rsync @staging:%files/ @live:%files - You can use this command to Synchronize staging files to production.

  • $ drush sql-sync --structure-tables-key=custom @live @local - This command is used to Synchronize database from production to local, excluding the cache table.

  • $ drush cex @dev, $ drush cim @live - This command is used to export and import the configuration.

Since we did not cover all Drush Commands and their usage, it will be helpful for you if you can check out Drush.org and Drush Commands.

Okay so now you know what is Drush and Drush Aliases and how it makes life easier for both Drupal developers and site administrators. We recommend you to try out Drush Commands to find out what works well for your current project or requirements. But there are many more advanced commands that are really worth learning.

If you have any suggestions or queries please comment down let me try to answer.

Happy Drushing!

How to create custom token to be used in default mail message template in Drupal 8

Sometimes we need to do similar coding in different places, such as for account settings email templates (Welcome email template, Forget password email template, from UI to get the same results. In this scenario, it's always suggested to create a custom token and use that in different types of email templates (account setting email templates) from Drupal UI in [token:type] format.

In our previous blog, we explored about creating custom tokens in Drupal 7 and in this, we will take a brief look at what is token? How to create it in Drupal 8?

In the vein of first thing first, what is token?

Tokens are very small bits of data or text that we use or place into larger documents via simple placeholders, like [type:token], to create custom tokens. The Token module provides an API that is used to provide tokens for all other core or contributed module in a bunch and provide browsing facility for all available tokens in UI.

When we install Drupal in our system, some Drupal core modules has available tokens that we can use in our code as well as in account setting email templates. But as a beginner in Drupal 8, It's really difficult to find out which core tokens are available and to find this, we use Token module. 

See the screenshot below for an example of available tokens.

Available token

Requirements

Sometimes, we need to create custom tokens as per the project's requirement and for that, we need two hooks, namely

1. hook_token_into()
2. hook_tokens()

hook_token_into(): This hook will allow you to provide the information of types of tokens and placeholders of tokens.
hook_tokens(): This hook provides replacement values of tokens. Some parameters are needed for this hook. Click here to check the parameters.

Here, I am creating a simple token to print “Hello World!” text as token replacement parameter.

Here we are going to see how to create a simple custom token in Drupal 8.

Step 1: Create a custom module for this custom token. Here I am creating a custom module name custom_module that contains the below-mentioned files.

custom_token.info.yml
custom_token.module
custom_token.tokens.inc

Step 2: Create a custom_token.info.yml file

Step 3: Create “custom_token.module file”.

Step 4: Create “custom_token.tokens.inc” file. Here, I have added all the custom codes for custom token.

Note: You can put both hooks and require bubble metadata class in “custom_token.module” file directly without creating any .inc file.

Ones you create and install this module, you will find the newly created custom token is displaying into the Browse available tokens section.

Custom token in browser list

Now you can use this newly created custom token in Account setting Email section as the below format:

    [custom_token_type:custom_token_name]

See the screenshot below for an example

Custom token apply in template

Okay, so now you know what is custom Token and how to create it? You're also convinced that you've got something new to say about your subject. Go ahead! Try custom Token on your website and see what it can do for you. I invite you to comment below or ask any questions you may have. 

Below given is a presentation on creating custom tokens in Drupal 8.

 

My first experience of Drupal Training at Valuebound

Learning Drupal has never been this interesting!

Recently, I attended my first Drupal training session at Valuebound on this Drupal Global Training Day. Surprise to know that the session was free and you missed it!

Don’t worry! Drupal community believes in contributing towards the society by sharing the knowledge and conducting free training sessions across the world. Global Training days is one of those initiatives where experience developers from companies and local groups introduce newcomers to the Drupal community.

The introductory session by Nishant Kumar and Chirag Shah was very informative as it provided an overview of Drupal, its feature and future, growing market demand, current job scenario and most importantly, prominent brands using the CMS, such as UNFPA, Magento, Tesla, Yahoo.

Coming from a non-technical background, I found the sessions very useful as it helped me in learning Drupal’s Front and back-end development tools as well as to build my personal Drupal website. Just to let you know, there's a common misconception surrounding CMS that you can create and customize your website only if you have mounds of coding knowledge. But it is not. 

Drupal 8's accessibility support, content authoring, admin experience, configuration management, translation support, responsive themes and key core modules like views and ckeditor are some of the major advantages to give a hard blow to competitors like WordPress. 

In the later phase of the session, the team discussed on back-end development, which was particularly aimed at Drupal Developers with an intermediate-level knowledge of PHP and SQL. 

Topics covered 

The more advanced, developer-level classes were divided topic wise. Let’s check out the list of session covered. Don’t worry I won’t let you stuck in between and share links to important blogs that will help you in creating your own live Drupal website. 

Drupal 8 Folder structure: Well, the session started with a brief look at Drupal 8 Folder structure to have a better understanding of the protocols and what is where.

Installing Drupal 8: You can install Drupal 8 on your local machine as well as in Acquia free cloud. And if you are planning to speed up administrative and development tasks for your site then I will suggest you install Drupal with Drush command. By installing Drush, we can perform the useful actions simply by typing a command into a terminal for the actions that usually take multiple steps in a web browser.

Drupal overview and site-building: This session was particularly intended for all skill levels - best for those who have completed the Introduction to Drupal 8 course.

Configuration management is turning out to be an effective replacement for Features module as it helps in creating and modifying configuration entities easily. In this session, the mentors discussed what we can do through configuration like site building, content types, taxonomies etc. Further, Configuration management has been integrated into the Drupal 8 Core to let you make and verify site configuration changes in the development, staging and production environments. 

Contributed themes: Theming in Drupal has undergone a lot of changes since Drupal 7 and now Drupal 8 has become the most leading Drupal ever build and adding more feature compared to other CMS which are out there. For instance, Introduction of twig in theming part.

Views: The most installed module - Drupal Views - is now available as the core module. And you don’t have to search for the latest version separately. For the 1st timer, Views allows you to generate a dynamic query using easy to use UI.

Remaining sessions were on Drupal 8 module development, setting up local dev box for Drupal 8 website on Apache server and configuring Apache Solr 6.6.1 with Drupal applications to achieve fast product/content search for enterprise web applications and others.

When I completed the session, I was surprised at how much we can do with Drupal. My experience at Drupal training session gave me a moderate-level understanding of the platform. How about you? Did you attend the session this year, if not, then probably you missed something. But don’t worry! Valuebound and other Drupal companies conduct similar session every year and you can attend it next time.

Please share your experiences by commenting below.
 

Secure users private data from unauthorised access using SSL

As a member of development team, I used to develop web applications using Drupal CMS without worrying about HTTP or HTTPS as it has to be added by dev operational team in my organization. On the serious note “How the Secure Sockets Layer (SSL) prepended to the existing URL” and How does it make a huge difference? Why it is important to make your web URL prepend https instead of HTTP.

Today SSL has become an eye-glazing topic and people want to know more about it so that they can protect their data from unauthorized access. In this blog post, we will take a brief look at basics of SSL and discuss how to secure the website running on Apache with HTTPS. Don’t worry! It's not a rocket science and very simple to secure your site as well as private data. In between, we will also explore some examples of secured and unsecured websites. You may also like to check out how to install & configure Apache on Windows machine.

Note: HTTP is not an encrypted server, hence, prone to cyber attacks and malware. 

Scenario

What happens when we connect to any website by entering the URL, it looks for specific IP address and then connect you to that server. Ones you start making a frequent request for each and every event from the HTTP server, the data sent from your server becomes prone to attack as it is in clear text format. 

And during this process, eavesdropper gets an access to read the conversation and attempt to create severe problems by using personal credentials, bank details, and other sensitive data. This is one of the major loopholes of HTTP. In contrast to that https protects your data from unauthorized access. Saving from all these headaches. 

See the image below for an example of an above-mentioned scenario.

HTTP

Solution:

In order to overcome the above situation, we need to transform HTTP to HTTPS in an address bar. In HTTPS, S stands for Secure Sockets Layer (SSL), which is responsible for securing communication over the internet. 

Check out the address bar of below screenshot for an example of SSL enabled site.

Address bar screenshot

 

HTTPS is comparatively more secure than HTTP. When we connect to a website, it automatically redirects to HTTPS and after that browser checks the certificate and verifies from the certificate authority (CA). Remember, a bad certificate issued by CA causes system failure sometimes.

When we send information over HTTPS, note, we are safe to make online transactions and share important credentials as it is encrypted. Enabling https on your site protects you from eavesdropping and any other attack.

Below figure is an example of how HTTP and HTTPS work.

HTTP vs HTTPS

On top of that if you are marketing or promoting your website among others then you should be more careful and enable SSL. Enabling SSL helps you to place your website in the special category, called secure, which pops up on the address bar when you start searching.

However, the presence of HTTPS and lock screen on address bar is not enough to say your browsing is secured. Some hackers create lock icon and replace with favicon just to showcase secure website. Keep your eyes open for these technical glitches.

Secure connection

 

If you don’t find HTTPS indicator on the browser, it means you may be connected to an impostor website on a compromised network. Well, these are the basics and I guess this much knowledge is enough for SSL and how somebody can perform secure browsing over SSL. 

Let’s get some local set up to perform SSL. 

What I am running on 

I have XAMPP web servers that run on Apache. 

How can we achieve

To enable SSL, we have to configure three major files.

  1. Httpd-vhosts.conf
  2. Httpd.conf
  3. httpd-ssl.conf

httpd-vhosts.conf

At this place, we create hostname by adding some of the parameters to enable SSL for the local web.

Codes mentioned below belongs to my local instance.
 

# http

    DocumentRoot "C:/xampp/htdocs/api"
     
             Options All
        AllowOverride All
            Require all granted
     

# https

   DocumentRoot "C:/xampp/htdocs/api"
    ServerName api
    SSLEngine on
    SSLCertificateFile "conf/ssl.crt/server.crt"
    SSLCertificateKeyFile "conf/ssl.key/server.key"
   
       Options All
       AllowOverride All
      Require all granted
   

Once the SSL is enabled, your site is going to look similar to this.

SSL enabled site

Some of the important parameters that I would like to discuss here:

  • SSLEngine

To turn on secure communications using SSL, we need to add a separate block to our host file, where one would be for handling regular HTTP and another one for https. Just to let you know, SSL should be disabled by default in the main server as well as in newly configured virtual hosts.

Syntax:   SSLEngine on|off|optional
Default:  SSLEngine off

Module:  mod_ssl

Example: SSLEngine on
    

  • SSLCertificateFile

This certificate file holds X.509 Certificate public key for data encryption.

Syntax: SSLCertificateFile file-path

Module: mod_ssl

Example: SSLCertificateFile "conf/ssl.crt/server.crt"

  • SSLCertificateKeyFile

This file holds private key for the corresponding public keys, which is used in SSLCertificateFile to encrypt and decrypt the data. 

Syntax:  SSLCertificateKeyFile file-path

Module: mod_ssl

Example:  SSLCertificateKeyFile "conf/ssl.key/server.key"

  • httpd.conf 

Apache configuration file contains one directive per line. Main configuration is of server is always been pulled up from httpd.conf file. Httpd is capable of loading multiple module and configuration for your website.

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

To enable SSL make sure SSL is enable not comment out by [#]tag.
search for 

#Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf

 

  • httpd-ssl.conf

All SSL enabled from apache takes default port as 443. 
Make sure to remove the comment from DocumentRoot to allow SSL

##
## SSL Virtual Host Context
##

#   General setup for the virtual host
#DocumentRoot "C:/xampp/htdocs"

Location: C:\xampp\apache\conf\extra\httpd-ssl.conf

This post is all about transforming your HTTP to HTTP(S), which is required to secure transmission & avoid eavesdropping. I have performed this on my local machine. In a similar way, you can do it on the real-time web application on the web server. To get the verified certificate, you can get in touch with web hosting distributor or third party or create your own self-signed-certificate to list your website in the generic list and Top Ranking.

Enable SSL on your website and see what it can do for you. Also, if you have any suggestions or queries please comment down and let me try to answer.

Planning to attend next Drupal Camp? Here are 6 things you should look for

Attending Drupal Camps has always excited me, reassuring faith on open source platform for building amazing digital experience. Drupal Camp Pune 2017, which was held at Symbiosis Institute of Management Studies, was such an event. Though it is bit late but worth sharing such an amazing experience.

Considered I am fairly new to this tightly-knit Drupal Community where developers and other enthusiasts are quite active in sharing their learning experiences. In July, me along with my colleagues - Puja Kumari and Suchitra Kumari from Valuebound - participated in Drupal Camp, and returned with new ideas, challenged assumptions, professional relationship, and others.

Not to mention, it was an amazing time meeting professionals, Drupal enthusiasts, college students and job seekers. The Camp received a remarkable response from more than 200 participants as expected. For the event, Valuebound - Drupal services specialist, Bangalore was one of the sponsors along with Acquia, Srijan Technologies, Innoraft Solutions, QED42, Drupalize.Me and OpenSense Labs.

Drupal Camp Pune 2017

Here are the six takeaways from Drupal Camp Pune 2017:

  • At the camp, we met a lot of enthusiasts who believe in open source platform and looking forward to work in Drupal.
  • Seeing the enthusiasm and energy of Drupal developers, many recent college grads and experienced employees enrolled for the ongoing hiring process.
  • It gave us golden opportunity to meet like-minded people and understand how leading organizations leverage the benefits of Drupal to reach their estimated goals.
  • The camp also helped me in understanding the importance of teamwork, community, and contribution towards Drupal.
  • Most importantly, it was an awesome time attending the Camp and met people having the same destination but different paths to success.
  • Notably, there were some excellent sessions. One of the sessions by featured speaker Rakesh James, who spoke on “why we need to invest in Drupal 8 and its future”, received great response from Drupal enthusiasts.

Drupalers

Following the session, we also hosted a range of fun-filled activities that engaged quite a lot of participants from the Camp. Many people also grabbed goodies as a souvenir.

Drupal Camp Pune Participants

It was a great time to attend the event. The Drupal community is more than just drupal.org where everyone is happy to discuss problems and share ideas. Not to mention, it left a beautiful memory and inspiration for forthcoming community events. 

With this, we look forward to being hosts once again like Drupal Camp Mumbai 2017 and  Drupal Camp Bangalore 2015.

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