How to enhance your content authoring by adding custom CKEditor plugin in Drupal 8?

CKEditor is a popular WYSIWYG (What You See Is What You Get). In Drupal default WYSIWYG editor is CKEditor. CKEditor has many of its own plugins.

Recently I got an opportunity to work for some top level media companies like Time Inc and Farm Journal with my Valuebound Teammates. It was a challenging experience , especially on the area of content creation and management work flow.  

We got a requirement where “Content Authors” should be able to upload the images in between  paragraphs of content. When the end user clicks on those images, the image has to be shown as a popup. So we decided to create a CKEditor plugin so that the users who are having  “Content Author” or “Content Editor” roles will be able to upload the image which will show up in a popup when it’s clicked. Because of this requirement, we were fortunate to develop a module called Simple Image Popup and  contribute back to Drupal Community.

Here we are going to see how to create a new plugin for CKEditor in Drupal 8, which inserts image wrapped in anchor tag.

Steps to create CKEditor plugin.

  1. Define and add basic plugin info in hook_ckeditor_plugin_info_alter() in your module file.
    File: my_module.module
     
  2. Define MyPlugin class which defines plugin, extending CKEditorPluginBase and implementing CKEditorPluginConfigurableInterface. In this plugin class we need to define the following methods:
    File: MyPlugin.php
    1. isInternal - Return is this plugin internal or not.
    2. getFile - Return absolute path to plugin.js file.
    3. getLibraries - Return dependency libraries, so those get loaded.
    4. getConfig - Return configuration array.
    5. getButtons - Return button info.
    6. settingsForm - Defines form for plugin settings, where it can be configured in ‘admin/config/content/formats/manage/full_html’. For example, this form shown below is where we can set the max size, width and height of the image, against which image will be validated when uploading an image.CKEditor Plugin setting form.

       

  3. Define client side plugin.js. Basic things we need to implement in plugin.js are:
    File: js/plugins/myplugin/plugin.js
    1. Add the new plugin to CKEditor. In beforeInit method we have to define our plugin command and add UI button which in turn triggers our plugin command on click of UI button as follows,
    2. Define routing for the dialog, which points to Form controller.
      File: my_module.routing.yml
    3. Define plugin dialog form and its form submit handler as we normally do in Drupal 8. In addition, on form submit we need to return ajax response command like below
      File: my_module\Form\EditorImagePopupDialog
      And whenever edit operation happens we need to populate existingValues json object in plugin.js file, so we can get those values in buildForm with the below line of code.

Finally configurations.

  1. Go to ‘admin/config/content/formats’, then click on configure action link for which format this plugin needs to be added.
  2. In configuration form, we can drag and drop newly created plugin button to CKEditor toolbar.
  3. Now, save the configuration form.
     

Hurray…! Now we can use our newly created CKEditor plugin. For more reference, find the contributed module, in which we have created CKEditor plugin for Drupal 8 Simple Image Popup.

How to reduce your development hours by Creating an Installation Profile or Distribution in Drupal 8!

Creating an installation profile in Drupal 8 is quite easy according to my humble opinion. Why? Because of the Configuration Management System in Drupal 8. In Drupal 7 we had lot of amazing contributed Installation profiles like Commerce Kick Start, Open Atrium, aGov, etc. Here we are going to discuss about how to create the installation profile in Drupal 8 and the benefit of using an installation profile in our Drupal Development World. Before that let us find out the answers for the following questions….

  • What is the Usage of installation profile?

  • Why do we need to create installation profile?

  • When do we need to think about architecting an installation profile?

  • How to reduce the development hours by creating an Installation Profile or Distribution in Drupal 8?

Thank God, I was one of the fortunate to work along with my Valuebound team members for some top Media companies like Time Inc and FarmJournal Media. All of these companies have a lot of websites with similar basic features, so it makes sense to create an installation profile with the basic set of features / functionalities. Similarly, developing websites for Universities, each University will be having multiple websites for different departments and branches. By creating an installation profile or distribution for the same, with the basic set of features will ease the development and deliver the Websites on time. Why? Because it reduces more than 30% (minimum) of development time. Thunder is one of the best example of an installation profile / distribution created by the media publishing company Hubert Burda Media.

How to create installation profile in Drupal8?

There are couple of steps involved in it, which is

  1. Selecting the machine name for the installation profile.
  2. Creating the Structure.

Selecting the machine name for the installation profile.

In this step we can decide what should be the machine name for our profile. Suppose our profile name is ‘Example Profile’ and machine name for this will be ‘example_profile’. The machine name can contain only lowercase letter and underscore.

Creating the Structure.

The structure has following files.

  1. Profilename.info.yml
  2. Profilename.profile
  3. Profilename.install
  4. Config folder.
  5. Translation folder(optional).

All the above steps should be inside the ‘/profile/your_profile’ folder under your ‘Drupal root Folder’. Here our profile name is “Example Profile”, So we have to do the action under the following directory.

“Drupal_root_folder/profile/example_profile”

1) Creating the Profilename.info.yml

Here we are creating the ‘example_profile.info.yml’.

In the ‘example_profile.info.yml’, We are having the following terms.

  • name:  This the name of  your profile.
  • type: What type it is whether it is module, theme or profile. Here we having ‘profile’.
  • description: Describe about your profile / distribution.
  • distribution: (Optional) Declare your installation profile as a distribution, This will make the installer auto-select this installation profile. The distribution_name property is used in the installer and other places as a label for the software being installed.
  • dependencies: Required modules.

2) Creating profilename.profile

.profile file is very much like .module on the module. It has all the access like .module has. Here we having ‘example_profile.profile

3) Creating profilename.install

In this file provide Install, update and uninstall functions for the profile.

4) Config folder

Config folder makes the difference from Drupal 7 to Drupal 8. Because of CMI in Drupal 8, it is very easy to add the features or function as config files under ‘config/install’ in your profile root directory. You can import the configuration from an existing site and keep it in in the ‘config/install’ folder. For an example we have created and exported the configuration for a view called “Example View For Example profile”. But we need to carefully follow the couple of steps which are mentioned below,

  • Copy all of the modules and themes listed within core.extension.yml into your profile's info file (using the new info file's format).
  • Delete core.extension.yml, file.settings.yml and update.settings.yml
  • Remove all of the UUIDs from your config files so that they don't conflict with those of new sites. Use phpstorm and  use following regular expression in the ‘Replace option under  Find in View options’. [View >> Find >> Replace]         
    “^uuid: .*\n”

Please check the following image for more clarity.

Installation Profile

Now our installation is ready to use.

The source of our example is: https://github.com/rakeshjames/example_profile

Conclusion:

If you are developing  ‘x’  number of websites having basic features / functionality / requirements which are similar, then it is always good to consider  creating an installation profile and Keep it. So that it will save at least 30% of overall development time. Which means you can use that time more effectively on your development to manifold your productivity.

How to create Form table in Drupal 8

In one of our project we came across a scenario where we need to update/delete the user field values based on the user detail. These can be seen on the users administration page (admin/people) or the content administration page (admin/content), There we will use this form table In these cases changing forms into a table of information helps us to do operations such as delete or edit in the form submit.

In this blog, I will be putting together a table form that looks like the following one

Table form   d8.png

Step 1:

Get the data:

The first thing we need to do is 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, am fetching user detail and creating the array

$query = \Drupal::database()->select('users_field_data', 'u');
$query->fields('u', ['uid','name','mail']);
$results = $query->execute()->fetchAll();

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 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 of username and one 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:

$header = [
     'userid' => t('User id'),
     'Username' => t('username'),
     'email' => t('Email'),
   ];

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.

// Initialize an empty array
$output = array();
// Next, loop through the $results array
foreach ($results as $result) {
     if ($result->uid != 0 && $result->uid != 1) {
       $output[$result->uid] = [
         'userid' => $result->uid,     // 'userid' was the key used in the header
         'Username' => $result->name, // 'Username' was the key used in the header
         'email' => $result->mail,    // 'email' was the key used in the header
       ];
     }
   }

Step 4:

Form Table

So now we have built a header ($header), and the rows of the table ($options). All that is left is to 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:

 $form['table'] = [
'#type' => 'tableselect',
'#header' => $header,
'#options' => $output,
'#empty' => t('No users found'),
];

That's it. This is simple table form with the list of user from the database and display in the table form,

In the next blog will discuss about the table form with the pager.

Drupal 8 Why & How to Migrate - Part1

 

As I was working with the migration towards Drupal 8 scenarios, I was pondered with this question of why are we migrating to Drupal 8 and how to go about it. So, I decided to go ahead and share a few case scenarios which will be helpful for you in case you are looking forward to gather info on Drupal 8 migration. This guide will be useful who are looking for a basic idea of Drupal 8 & migrating to the same.

We will look into migration of different entities in the upcoming articles. In this article I will be explaining about term migration.

WHY Migrate?

The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a website from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are also included - it can easily be extended for migrating other types of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands.

In one of the recent projects, we needed to migrate terms,nodes and author from external sources. For this scenario  we are implementing our own migration script.

HOW to migrate?

For implementing migration script, there are some dependencies for which you need to install all the required modules which are listed below.

Migrate Module (Included in Drupal 8 core)

The migrate module provides a flexible framework for migrating content into Drupal from other sources.

Related: How to migrate your website to Drupal 8

Drupal Console
The new CLI for Drupal. Drupal Console is a tool to generate boilerplate code, interact and debug Drupal. From the ground up, it has been built to utilize the same modern PHP practices which were introduced in Drupal 8.

Migrate Plus
The migrate_plus project contains three modules:

  • migrate_plus - Extends the core migration framework with additional functionalities to tweak incoming source data in migrations, also to code examples for making custom migrations
  • migrate_example - A carefully documented implementation of a custom migration scenario, designed to walk you through the basic concepts of the Drupal 8 migration framework.
  • migrate_example_advanced (still in progress) - Examples of more advanced techniques for Drupal 8 migration. 


Migrate Tools

Drush commands supported include:

  • migrate-status - Lists migrations and their status.
  • migrate-import - Performs import operations.
  • migrate-rollback - Performs rollback operations.
  • migrate-stop - Cleanly stops a running operation.
  • migrate-reset-status - Sets a migration status to Idle if it gets stuck.
  • migrate-messages - Lists any messages associated with a migration import.

To use Drupal with Drush in Drupal 8 it requires a minimum of Drush version 8. Before you get your hands dirty, you can go thru' this article on Custom Drush commands in Drupal 8. This should give you a good understanding about writing custom Drush commands in Drupal 8. It is not exactly like Drupal 7 but similar.

First, connect Drupal with an external database and add this code in settings.php
We are going to instruct migrate source to use this database target and use the key name as “source_migration” which will be  used in every migration file.

Here we go, with our Custom script for creating Taxonomy Term From External Source.

Which will eventually help to organize your site by assigning descriptive terms to each piece of content

Open terminal and enter 

drupal migrate:debug

As our migration resources are not showing yet we have to create a custom module for this. We can do this by the following steps -

  1. Create folder for custom Drupal module in my Drupal site: /modules/custom/migration_fj
  2. Create a new file migration_fj.info.yml with below code
  3. Migration plus module allows you to specify even the migration group. For grouping our migration we need to create a config entity. Create a new file migration_fj.migration_group.fj.yml using code below in the module folder custom/migration_fj/config/install/

    Here we have used our Key “source_migration” for connecting migration script with external database from where we would be fetching the content.

  4. Now let’s move on to defining source class.

    In our project, we needed to import category from a custom application as taxonomy terms in Drupal. In this case, the category didn’t have unique ids, instead, it was just a column having table name as a category with the values in rows.

    To create source class, create a new file.
    custom/migration_fj/src/Plugin/migrate/source/FjTerm.php
     

  5. Now for term migration, we need to create a new config entity.
    custom/migration_fj/config/install/migration_fj.migration.fj_term.yml

Our module is complete and ready for term migration using Drush. Now we can execute it with the migrate_tools

drush migrate-import example_term

Related: Migrating address book using process plugin in Drupal 8

WHAT if you have to roll it back?

For rollback, we can use drush migrate-rollback

I hope now it will be easier to migrate to Drupal 8.

Comment below if you come across any difficulties during the process. Read more of my experiences with Drupal.

Read More Relevant: How to migrate Users from a CSV file in Drupal 8?

Ref:
http://studio.gd/node/5

How to Render a Slideshow using new module imagefield_slideshow


Overview of the Module:

This module is developed specifically to render the slideshow from the image field.
Imagefield Slideshow module will provide a field formatter for image fields, so that multiple images are uploaded to that particular image field and the formatter helps you to render those images a slideshow.

Potentially the administrator would be able to change the rendering settings of the slideshow like transition effects and image size to render.

Works with all entity display formatters like node, user  etc, and also with the views module.

 

How to install the module?

  1. Create a libraries directory on your drupal instance's root folder.

  2. Create a directory within libraries named jquery.cycle.

  3. Download the latest version of the jQuery Cycle plugin (http://jquery.malsup.com/cycle/download.html) place it inside the jquery.cycledirectory. The filename should be: jquery.cycle.all.js

  4. Enable the Imagefield Slideshow module from the modules page.

  5. You should now see a new field formatter for image fields display settings
    Ex: under Manage display section of content types


How to configure the module?

When you visit any image fields display settings, you will be able to find the Imagefield Slideshow formatter, as shown in the image below.
Ex: admin/structure/types/manage/article/display

imagefield_slideshow1.png


You can configure the setting for rendering the slideshow, as shown in the following  image.
1. Select the image style required.
2. Then  select the transition effect to be applied in the slideshow.

imagefield_slideshow2.png



This module is best suited, if you need a unique slideshow on every node of a content type.


If you have new ideas to improve this module further, or want to customize it for your own projects feel free to contact us.
 

Drupal 8 Commerce is on the Way! DrupalCon New Orleans 2016.

A lot of thanks to the commerce guys for contributing the Drupal commerce module to Drupal community, which took drupal to a different level in the CMS world. Its very exciting, Commerce 2.x which is the Drupal 8 version of drupal commerce. As like any other drupal developer / architect, I am also excited about Commerce 2.x

Thank God, I was one of the fortunate ones to attend the Commerce Guys session on DrupalCon New Orleans 2016, the very first session after the release of ‘8.x-2.0-alpha4’  version of drupal commerce. It was an amazing session, which made a lot of things clearer,a lot of unanswered questions were answered by the Commerce guys themselves. Here we are going to discuss about the take away of the Commerce Guys session on DrupalCon New Orleans 2016.
 

No more Commerce Kickstart in Drupal 8, Why?

No more Commerce Kickstart in Drupal 8, because Commerce 2.x is developed as loosely coupled by using a lot of PHP 5.4+ libraries like tax [tax library], addressing [addressing library powered by Google’s dataset], intl [internationalization library powered by CLDR data], zone [zone management library]. Using composer we can create a new site as like commerce kick start in Drupal 7. For that we have to use the following command.

$ composer create-project drupalcommerce/project-base mystore --stability dev

 The above command will download Drupal 8 + Commerce 2.x with all dependencies to the ‘mystore’ folder. Before running the above command please make sure you have installed composer globally on  your system.

How to install Commerce 2.x on existing site?

For Installing Commerce 2.x in existing Drupal8.x site,  we need to do the following steps.

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://packagist.drupal-composer.org

 

Step 2: The following command will help 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 modules “commerce_product commerce_checkout commerce_cart commerce_tax” , Use drush or drupal console

Read more about the commerce documentation on: http://docs.drupalcommerce.org/v2/

The above steps help you to install the commerce 2.x on the existing site. Moreover  that in Drupal 8 commerce 2.x  requires lot of contrib modules developed and contributed by commerce guys themselves. The following ones are the famous ones.

  1. Inline Entity Form
  2. Address
  3. Profile
  4. State Machine

What is new in Commerce 2.x?

  1. Currency Management :  Integrated the Unicode CLDR project. So it is easy to use the currency inside and outside the US.                                                                                     
  2. Price Formatting: Price format  varies from country to country and language to Country.  Like German(Austria) Vs German(Germany)                                                                       
  3. Taxes: Imports the tax rates automatically on country basis depending upon the product like B2B, B2C, digital or physical products.                                                                           
  4. Stores: Multiple stores in same Drupal Commerce Instance, hence there will be majorly two types of use cases, first one is where User can create their own stores based on their own products. Which means multiple cart from multiple stores, from the buyer’s perspective. The Second one being this, that the Company has billing location in multiple countries.                                                                                                                                
  5. Products: Instead of nodes we hare having Product entity itself. On the production creation page using inline entity to create individual product variations. And those variations holds the SKUs and sets of attributes.                                                                  
  6. Product Attributes: In Commerce 2.x product attributes are its own entities, So it is easy to edit, delete, create new attribute from. Suppose you want to add the attributes to the product variation type,  you have to edit the respective production variation type and select the checkbox under the ‘Attributes’. So it is easy to use different form of modes to display fields.                                                                                                                           
  7. Order and Line Item Types: This will provide the option to have separate order types for different types of products like physical and digital products, event registration, training payment etc. So it s provide different checkout flow, different workflow, different logic  or different experience to the customers.                                                                                  
  8. Order Editing: Order is in step by step. Right columns provide the IP address  and the geo location of the order.                                                                                                            
  9. Add to Cart Forms: In the add to cart forms,we can have the variation attributes fields and line item fields as well. Now we have full control add to cart forms powered by Form display mode and field widget plugin.                                                                                   
  10. Shopping Carts: If you having multiple shopping carts, the ui will help to see and checkout each of them separately.                                                                                        
  11. Shopping Cart block: Easily customizable shopping cart block.                                           
  12. Checkout Flows: You can define your own custom checkout flows.                                    
  13. Improved Checkout UX:  It provides the option to do checkout as a guest user, or can also be registered as a new user while doing checkout.                                                       
  14. Payments: Under active development, Currently integrating Braintree and Authorize.Net as reference implementations.                   

Conclusion

Early in 2017 or even before Commerce 2.x will be fully functional. Commerce 2.x  with Drupal 8 will make a difference in the ecommerce world.

When can we start using the Drupal8 Commerce 2.x ?

See the bellow comment by Bojan Živanović

Thanks, that's a great summary. We're tracking the beta1 blockers here: https://www.drupal.org/node/27..., once beta1 gets released people will be able to start building production sites on Commerce 2.x. See you in the issue queues!

Image credits: https://www.flickr.com/photos/comprock/26392816934/in/pool-drupalconneworleans2016/

Send Message to Slack from Drupal

We moved to Slack few months back and the one thing that I love about Slack, is the integration of various apps with it. Most of the integration are out of the box like Google documents, Dropbox, Git and Bitbucket. But we wanted to integrate Drupal with it. Our need was to send a notification message to the #general channel whenever a new Blog post is published.

We start off by adding a Custom Integration from the Slack App Directory.

Salck custom integration

We will be using the Incoming Webhook as we will be sending data from our Drupal site to Slack.

Select the channel where you want to post the message or create a new one. Once the channel is selected it gives you the setup instructions. The most important part is the Webhook URL which we will be used in our Drupal site. You also get a level of customisation about the slack bot like the name and image.

Next we come to our Drupal site. Drupal 8 has a development release for the module which allows integration of Slack. Once the module is installed go to Slack configuration page at “admin/config/services/slack/config”. Here you will enter the Webhook Url as provided by Slack when the integration was added. Additionally you can also change the username and image of the username who will be sending the message to Slack.

Slack configuration


Try sending a test message from the Slack configuration UI and when everything is setup correctly you will receive a message in Slack.

Now, to send a message to Slack when a node is created or update add the following code:
 


/**
 * Send message via slack.
 * @param $node
 * @param $op
 */
function send_message($node, $op) {
 global $base_url;
 $config = \Drupal::config('slack.settings');
 $channel = 'test';
 $url = Url::fromUri($base_url . '/node/' . $node->id());
 $node_title = $node->label();
 $snippet_user_id = $node->get('field_user')->target_id;
 $account = Term::load($snippet_user_id)->getName();
 $username = $config->get('slack_username');
 $link = render(Link::fromTextAndUrl("here", $url)->toRenderable());
 $webhook_url = $config->get('slack_webhook_url');
 
 if ($op == 'insert') {
   $message = 'Snippet `' . $node_title . '`` was added by *' . $account . '*. Click ' . $link . " to view.";
 }
 else {
   $message = 'Snippet `' . $node_title . '`` was updated by *' . $account . '*. Click ' . $link . " to view.";
 }
 // This will send your message to Slack.
 \Drupal::service('slack')
   ->sendMessage($webhook_url, $message, $channel, $username);
}

 

Salck message


Finally we are trying to integrate Disqus comments with Slack so that when there is a new comment we get a notification about it and respond. 

There you go!
 

Get To Know About Postman Tool

Postman is a great tool for prototyping APIs, and it also has some powerful testing features. So, here I share how to integrate Postman's tests into your build automation to make it elite. I've used Postman in one of my projects as a way to interact with APIs which is also explained here. As a tool to setup complex HTTP requests, this is  much convenient than request specs, Cucumber, or hand-rolling them in even your favorite HTTP library.

A Little About Postman
Postman is a Google Chrome app for interacting with HTTP APIs. It presents you with a friendly GUI for constructing requests and reading responses. The people behind Postman also offer an add-on package called Jetpacks, which includes some automation tools and, most crucially, a Javascript testing library. This post will walk you through an example that uses those testing features. While they won't replace your focused unit tests, they do breathe new life into testing features from outside your applications. This makes it extremely valuable for functional testers or for developers who love to test outside-in.

HTTP VERBS generally used in POSTMAN
GET : Read a specific resource (by an identifier) or a collection of resources.
HEAD : Works same as GET, just returns the header.
PUT : Update a specific resource (by an identifier) or a collection of resources. Can also be used to create a specific resource if the resource identifier is known before-hand.
DELETE : Remove/delete a specific resource by an identifier.
POST : Create a new resource. Also a catch-all verb for operations that don't fit into the other categories.

HTTP Response Codes for Status
Using top 10 HTTP status codes

200 – ok – general success
201 – created – New resource has been created
204 – no content – Success and response body empty. The resource was successfully deleted.
304 – Not Modified – The client can use cached data
400 – Bad Request – The request was invalid or cannot be served. The exact error explained in error payload.
401 – Unauthorized – The request requires an user authentication
403 – Forbidden – The server understood the request, but is refusing it or the access is not allowed.
404 – Not found – There is no resource behind the URI
405 - Method not allowed
422 - Unprocessable Entity
500 – Internal Server Error

You have to get the POSTMAN from https://www.getpostman.com/ and download the google chrome POSTMAN extension and signup for free to create an account. After creating the account when you log in to the POSTMAN tool, you have to have the URI to test ,whether the URI gives the correct response or not ,after verifying the results and codes.

Steps for doing  the API Testing using POSTMAN.

Step 1: Open POSTMAN tool and log in with your credentials.
Step 2: Get the Request URL(Uniform Resource Locator) of the API.
Step 3: Paste that URL into the URL space given in the POSTMAN.
Step 4: Select the Method which you want to perform,For example GET,PUT,POST,DELETE.
(Note: The endpoint of the URL would be different for different Methods).

Step 5: Put the Headers with Key and Value field.
Step 6: Put the body part and select raw option ,incase you are using any POST/DELETE Method.
Step 7: Recheck the given URL and click on send button and observe the response in JSON format.

*Let us take a scenario of creating a new profile in a XYZ website and after creating that new profile we will try to retrieve its data from the DB using POSTMAN Tool.
 

Pre requisites:
1. First, user has to logout from the XYZ website,and we need to have a resource endpoint to which we are posting the new profile.

2. We would also need the body part of the profile what we are posting.

3. After successfully creating the new profile we have to make the Request URL from the response, to fetch that newly created profile.

Step 1: Get the request URL and paste in the URL space provided in POSTMAN.
ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles

Step 2: Select the POST Method.

Step 3: Put the headers and body part and select the raw option of input type for Body part.
Headers:

Content-Type  : application/json

Authorization : Bearer 60557ad5f4ddd047c846928642b7aab1b94f3681

X-CSRF-Token : eMb4uODH3rNwb6r-SUt6rb9mPWtu69kdoAjcbIGgOMQ

Body Part:

{"name": "ABCD",

"account" :

{ "is_new": 1, "email": "abcd@gmail.com",

 "password": "password" }

}

 


Step 4: Click on the Send button and observe results.

Response would come in JSON Format:

Status code: 201 Created

{  "id": "438b5097-57c9-411f-9e4f-abd04192b2d1", "href": "ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1",

  "type": "profile",

  "account": {

"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/account",

 "data": { "id": "d76c0eda-2525-43d0-b9bf-69fe84860cfc",

"name": "1qw111ww2.singh",

"email": "1qw111ww2.singh@david.com",

 "created_time": "1463050948",

 "last_login_time": "1463050948",

 "status": "1",

 "email_verification_status": "0",

"phone": "",

"phone_verification_status": "0",

"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/accounts/d76c0eda-2525-43d0-b9bf-69fe84860cfc",

"type": "account",

"profile":{"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/accounts/d76c0eda-2525-43d0-b9bf-69fe84860cfc/profile",

"data": [

{

"id": "438b5097-57c9-411f-9e4f-abd04192b2d1",

"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1",

"type": "profile"

}

 ]

},

"session_id": "cXH295AMUKo5nx40aNhIwtNmo3c9x8WQrLu9uCMSBQ8",

"session_name": "SESS15dfa26f31ea72e21097a903a2b1b263",

"token": "dTbg9wLVhpqT2ShezRq7orHl5zTJxEwbPlflsxIJinY"

}}}</pre>

 

Screen shot of the Response:

Postman Screenshot

Now We have successfully created a new profile.Let us now retrieve the profile data that we just have created,from the DB through below request URL.

Request URL:
ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1

Response:  200 Success

{

 "id": "438b5097-57c9-411f-9e4f-abd04192b2d1",

"name": "A2?!@B=22A",

 "cover_picture": {

"thumbnail":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/sites/default/files/styles/thumbnail/public?itok=zcW4M1JC",

"medium":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/sites/default/files/styles/medium/public?itok=2poEpR1K", "large":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/sites/default/files/styles/large/public?itok=OcLV1fUn"

 },

"about": null,

"short_bio": null,

"gender": "",

"display_picture": {

"thumbnail":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/sites/default/files/styles/thumbnail/public?itok=zcW4M1JC",

"medium":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/sites/default/files/styles/medium/public?itok=2poEpR1K",

"large":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/sites/default/files/styles/large/public?itok=OcLV1fUn" },

"created_time": "1463050948",

"updated_time": "1463050948",

"status": "0",

"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1",

"type": "profile",

"location": {},

"connection_request_count": "0",

"events": {

"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/events",

"data": []

},

"account": {

"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/account",

"data": [{"id": "d76c0eda-2525-43d0-b9bf-69fe84860cfc",

"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/accounts/d76c0eda-2525-43d0-b9bf-69fe84860cfc",

"type": "account"

}]},

"works": {“href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/works",

"data": []

},  "current_campus": {

"href":”http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/current_campus",

"data": []},

"Educations":

{"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/educations",

"data": []

},

"reading_list": {

    "href": "http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/reading_list",

    "data": []

  },

  "skills": {

    "href": "http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/skills",

    "data": []

},

"connections": {"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/connections",

"data": []

},

"connections_mutual": {“href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/connections_mutual",

"data": []

},"followers": {"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/followers",

"data": []

},"profiles_following": {"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/profiles_following",

"data": []},

"topics_subscribed": {"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/topics_subscribed",

"data": [

{

"rel_created_time": "1463050948",

"id": "74501461-5f98-407a-b7c0-90846058accb",

"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/topics/74501461-5f98-407a-b7c0-90846058accb",

"type": "topic"}]},

"stories": {

"href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/stories",

"data": []

},"calendar":{

“href":"http://ec2-54-238-127-209.ap-northeast-1.compute.amazonaws.com/v1/profiles/438b5097-57c9-411f-9e4f-abd04192b2d1/calendar",

”data": []}}

 

Image of newly created profile retrieval.

Postman Screenshot

Your First Step to Git

Hey! So you are here in this page trying to find/learn something about git! Have you used a source code management system to synchronize your local code remotely before? Do you know that Git is the most powerful SCM. I was convinced and yes it is!

I have actually started SCM with svn( Apache Subversion). In fact started with TortoiseSVN, a GUI tool for Windows. Here there are no commands, no need to remember, so, nothing to worry, Just right click on your web root folder and choose whichever option you need! Sounds easy?

If you want to go with SVN, you can refer these links.
http://www.tutorialspoint.com/svn/svn_basic_concepts.htm
 

However I would suggest you to try Git!  You can ask me why? Well, It’s New! It’s Challenging! And you definitely enjoy it! You can simply follow this to understand working with Git.

Every Git working directory is a full-fledged repository with complete history and full revision tracking capabilities, which is not dependent on network access or a central server.

Git can be really confusing at first when working decentralized. Many questions would be running in your head, like,’ how to start with it?’, ‘how to properly set up the initial repository?’ etc. Assume you do not have the internet and you had some changes that are to be committed, now if its svn, you have to literally copy/paste. But if its git, you can still commit your changes locally using git commit and then push your changes to master using git push origin master. Unlike SVN, yes, Git adds complexity. You heard me right. Git commands like commit vs push, checkout vs clone, all you have to know is which command works locally and which works with server. Still Git seems to be the cool thing. It’s faster than svn.


Git is distributed, SVN is not:

Git like SVN do have centralized repository or server. But, Git is more intended to be used in distributed mode which means, we can actually checkout the code from central repository to our own cloned repository on our machine. Once you made your changes and you do not have internet connection, you will still be able to commit your changes locally, or create a branch locally and commit in that branch. Once your net connection is back, you can then push your changes to the server.

So what do you mean by branch system? Let’s say, I have a project and I want to subdivide my project in 3 parts - design, development & configuration and also assign to 3 different

people(p1,p2,p3). I will create 3 new branches for each person, other than the master branch. Let me take you through the workflow.


To create a branch:
git checkout -b branch1 master  -> creates a branch locally with name branch1 as a child of master branch., similarly will create 2 more branches branch2, branch3. Myself p1, had made some changes in my branch branch1.

Git repositories usually are much smaller than Subversions.  If you want a dump of code that is already present in Git, you can get the code repository using git clone.
git clone
You can find the link in the repository page in Github. Make sure you add the link with ssh protocol, instead of https which would require basic authentication(username and password) but ssh tries to use the ssh key.

If your project is all new and you want to share this, you will have to initialize the directory you are working on. Go to the directory and type the following:
git init
This initialises your local repository as git repository and now you will be able to commit the local changes to git.Verify the files which are changed. Do git status for this.

Check the difference of what is added or deleted in each changed file.


git diff -> shows diff of all the changed files.
git diff ”  -> shows diff of specified file

To commit:
git commit -am "commit message"
am - adds and commits the files with message.


To Add the files:
git add .

To add a single file
git add


To Commit the added files.
git commit -m "commit message"


You want to remove a file/folder that is already added/committed:
git rm -f


You want to modify the committed message:
git commit --amend -m "New commit message"


This changes the message of last commit, only if its not yet pushed.

You have committed the changes locally. Now you want to sync all the branches with same code changes. For this you have to push your changes to the server. But before pushing, I want to sync my branch as of master.
git pull remotename branchname


Eg: git pull origin master -> pulls the master code. Or You can fetch and then merge.
git fetch
git merge origin master

In this case, we might sometimes get a conflict if there are changes done for same file, on same line number in master and in local. In this case you have to make the changes required to avoid the conflict and commit the files again(git commit -am)

Now, push the local changes:
git push origin branch1

Done!! Simple! These are the basic beginner commands you would need to push your changes.
You wanna play more with git?
Git asks for user credentials each time you try to push your changes or while requesting pull. To avoid this, as said earlier you will have to add the ssh key to your git account.

To check the git user's info.
git config -l

Here are the steps to add ssh key.

Step:1
In Terminal, Paste the text below, substituting in your GitHub email address.
ssh-keygen -t rsa -b 4096 -C "email_id@example.com"
This Creates a new ssh key, using the provided email as a label


Step:2
When you are prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location(/Users/you/.ssh/id_rsa).

Step:3
Enter passphrase: [Type a passphrase or click enter if you want it as empty]
Enter same passphrase again: [Type passphrase again]
Now the key is generated.


Step:4
Ensure ssh-agent is enabled:
eval "$(ssh-agent -s)"


Step:5
Add your SSH key to the ssh-agent.
ssh-add ~/.ssh/id_rsa


Step:6

  1. Adding the public key to your git account.
  2. Open /home/you/.ssh/id_rsa.pub copy the key to clipboard
  3. Login to github, Click the profile photo on top right corner, then click on "Settings"
  4. In the user settings sidebar, click SSH and GPG keys.
  5. Click New SSH Key.
  6. In the title add a descriptive label for the new key, Paste your new key in the "key" field.
  7. Click Add SSH Key

    Done! You will not be irritated by asking credentials anymore.

Sometimes you will be asked to perform one more step, incase there is a maintainer who merges all the branches. Login to git, open the new branch created and create a pull request, So that other branches can pull these changes. -> click on Create Pull Request.


This is the basic flow you would initially need to commit your local changes to server. Few of other commands that you need are:
You have modified a file and now you don't need those changes anymore,
git checkout resets the file to the last committed version.
Multiple files can be separated by space.

To delete a branch locally
git branch -D


You don’t need any of the changed files, and want to revert to last commit:
git reset --hard

To reset to a particular commit, use following
git reset --hard
eg: git reset --hard 1db6d9af7b6e3b1ebb7e9912ee514e9b50f85af1


To reset to last merge,
git reset --merge ORIG_HEAD


Let’s say you have made some changes to few of the committed files. Now, If you want to save the changes temporarily for single file, may be you will do a copy/paste, but if it's more than one file, it's annoying to copy/paste all the changes.
git stash
This reverts all the files to the last committed version saving the changes temporarily.

You want to get back the saved changes,
git stash apply


You want to ignore a file while committing, instead of adding each file, ignoring a single file from the list of changed files would look more better. Also there is no need to avoid this each time. So, for this you have to navigate to the location of your git repository, create a file .gitignore file and list out the the files or directory.
Example: I want to ignore my settings.php file, and a directory test. For this, add the files like below.


mysitefolder/sites/default/settings.php
mysitefolder/sites/default/files/test/*

...
..

You can actually commit this file if you want to ignore any changes blindly,and  to share with any other users when they clone the repository.


If you want to do ignore a file locally,
git update-index --assume-unchanged settings.php


To get the last commits:
git log
To get commit details of last n commits.
git log -n

Oh My God!! Too many! Looking Kind of complex? But trust me, Git may be harder to learn, but once you do learn how to use Git, you’ll find it to be feature rich and functional.  Git, Do have the GUI as well if you wanna give it a try, like smart git, source tree etc. Of course, Subversion's UI is more mature than Git's. I feel like git is even more reliable. No limits to explore! So you can still go around the web to find more interesting things about Git!

 

Create Apache2 Virtual Host using Shell Script

The ability to create and utilize tools, makes human race dominant in world. Tools make our work easier and also saves time. One of the tools, I am going to share is bash shell script to create apache2 server virtual host.

Why Virtual Host?

Using virtual host we can run more than one web site (such as dev.drupal-cms.com, stage.drupal-cms.com and www.drupal-cms.com) on a single machine. It can be "IP-based" or “name-based”. In IP-based you can have different IP address for each web site. In name-based you can have multiple names running on each IP address.

Shell script code
 

Explanation

Script expects 3 strings as input:

  1. Domain name: Name of domain you wish to give for the site. Eg: drupal-cms.local or stage.drupal-cms.com or drupal-cms
  2. Full path to webroot: Full path to site webroot. Eg: /var/www/html/drupal-cms
  3. Server admin (optional): Site server admin email id. This is optional, default value will be ‘webmaster@localhost’

Script does the following to create a virtual host for apache2:

  1. Creates virtual host rules files inside `/etc/apache2/sites-available/` (line number 12 to 24)
  2. Creates an IP address mapping in ‘/etc/hosts’ file. Mapping would be like this 127.0.0.1 $name (line number 26)
  3. Enables the site, a2ensite $name
  4. Restarts apache2 server, service apache2 reload

Usage

  1. Download or clone the script from https://github.com/manoj-apare/Virtual-Host-Script
  2. Make it executable.
  3. Run the command: sudo [path-to-script]/virtual-host-script.sh [domain-name] [full-path-to-webroot] [optional-server-admin-email-id]


Note: third argument is optional.

CLI


That’s it. Now you can access the site using newly created virtual host by clicking the link printed by the script on CLI.

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