Batch Process in Drupal 8

Batch process is the process of execution of a program in a series without interference of external source manually. In a Batch process, inputs are taken in batches or slots. However, now this has become more irrelevant with the term batch and essentially means to run a process or a job without an end user’s interaction. In Drupal, batch process will help to execute a similar programme.

In this tutorial, we will go through how to create a drupal batch process.

 

For the process we need a controller or a form from which we can trigger the batch process. In our case we will create a batch process to delete all Node. 

So let’s create a small module for that.

Drupal module development

Module Setup:

batch_example.info.yml

Let’s create routing.yml

batch_example.routing.yml

src/Form/DeleteNodeForm.php

Here in the form we just need a submit button to handle the request.

Here in the submission handler where we have defined the batch. 

$batch is an array of steps to be performed in batch process. In this batch we have two steps,

  • deleteNodeExample : In this method we will be handling deletion of node.
  • deleteNodeExampleFinishedCallback: This is the finish call back it will be called once deletion of all node is done. It will give the status message of the process.
  • Batch_set : Drupal batch_set method will execute set of operations in made in batches, so as to not interrupt processing.  

Now we need to define these methods, So will create a class say “DeleteNode” inside src directory.

 

src/DeleteNode.php

This was all about creating batch process in Drupal 8. For testing the batch we can use drupal Devel module to create dummy content.



Advance Your Business: Drupal 8 Support Ends - Take Action!

 

Convert your favorite HTML5 Bootstrap Template to Drupal 8 Theme!

Quite a few times we come across Bootstrap themes when we wish to use in our Drupal website. You have searched Drupal download and it is not available as sub-theme. How about creating a new theme in Drupal 8 out of HTML template. In this post we are going to discuss, how we need to approach and build Drupal 8 bootstrap sub theme based on a html bootstrap template.

Bootstrap is html, css and js framework for building mobile first responsive themes. Bootstrap is available for Drupal 7 and 8 with starter kits using cdn and less. If you need to build your Drupal 8 theme using bootstrap starter kit, please go through this simple tutorial on How-to-build-your-drupal-8-theme-using-bootstrap-less. We have explained the basic folder structure of Drupal 8 theme in one of previous blog post - understanding-of-drupal-8-theming.

We will be creating Drupal theme out of this in following steps -

Creating sub theme

First we need to download the base theme bootstrap and place it in `/themes` directory in web root. Create new directory for sub theme, let say `my_sub_theme`. For sub theme, to be usable minimum we need is theme info.yml file. Info file would be like this initially,

Theme based on HTML bootstrap template

Step one: Identifying regions

First step in theming based on html bootstrap template is to find out possible regions in context of Drupal 8 site. List of region in Drupal site can be obtained from `admin/structure/block/demo/my_sub_theme`. For bootstrap, it will be like,

File: my_sub_theme.info.yml
Code:
name: my_sub_theme
type: theme
base theme: bootstrap
description: 'A simple starter theme for Drupal 8.'
core: '8.x'

Once info.yml file is been defined, we can enable the new theme. At this point if you view the page, what you would see is nothing simple and default bootstrap’s look and feel. Now the next part would be how can we integrate our html bootstrap template.

Bootstrap theme regions

Once you found out the possible regions and the regions provided by bootstrap is more than enough you can skip this section. If you need to alter regions, list them in info.yml file. Then only listing regions would be available for newly created theme.

File: my_sub_theme.info.yml
Code:
name: my_sub_theme
. .
. .
core: '8.x'

regions:
  header: 'Top Bar'
  help: 'Help'
  content: 'Content'
  footer: 'Footer'

Step two: Create libraries.yml

Make a list of css and js libraries is been used in all page template. Also figure out list of css and js libraries used only in some pages (says only pages which having forms). Once this listing is been done, we are ready to create libraries.yml file. Libraries need to be defined section wise, like libraries needed for all pages as one section and libraries needed for specific set of pages as separate section for each. Suppose let libraries.yml be

File: my_sub_theme.libraries.yml
Code:
theme: # Libraries needed in all pages.
  css:
    theme:
      css/font-awesome.min.css: {}
      css/animate.css: {}
      css/style.css: {}
      # External library
      http://fonts.googleapis.com/css?family=Lobster: { type: external }
  js: 
    js/jquery.appear.js: {}
    js/jqBootstrapValidation.js: {}
    js/modernizr.custom.js: {}
    js/script.js: {}
  dependencies:
    - bootstrap/theme
contact_me: # Libraries needed only in contact page.
  js:
    js/contact_me.js: {}

In this libraries.yml file you might have noticed, basic bootstrap css and js libraries are missing. Since my_sub_theme is sub theme of bootstrap, we can specify what all libraries needed from base theme as dependencies. In above code, we have given `bootstrap/theme` as dependency where first part (bootstrap) is theme name and second part (theme) is key of library defined in bootstrap.libraries.yml.

Done with defining libraries.yml. Now how do we use it or include it or attach it? Just include in info.yml. Same way you can include any other libraries you need in info.yml.

File: my_sub_theme.info.yml
Code:
name: my_sub_theme
. .
. .
core: '8.x'

regions:
. .
. .

libraries:
  - 'my_sub_theme/theme'

# List of css need to removed.
stylesheets-remove:
  - themes/bootstrap/css/3.3.5/overrides.min.css

Libraries specified in info.yml will be attached for all pages. We may need some libraries defined in libraries.yml need to be conditionally or for specific pages. This can be achieved by using template_preprocess_HOOK() in my_sub_theme.theme file.

File: my_sub_theme.theme
Code:
function my_sub_theme_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    $variables['#attached']['library'][] = 'my_sub_theme/contact_me';
  }
}

For more info, you can refer Drupal 8 documentation Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module on how to achieve it.

We can avoid or remove some css from base theme to be get attached using `stylesheets-remove`.

Step three: Modifying template

Modifying html to suit the HTML bootstrap template will be more difficult task initially, but i must say you will enjoy it and find it challenging to work in Drupal 8 after turning on twig debugging. For turning on twig debugging, rename the file `sites/default/default.services.yml` to `sites/default/services.yml` and change the value of debug from false to true under section `twig.config` and finally clear the cache.

Drupal services yml

Now onwards, you can get template info and template suggestions from browser developer tool. It looks like

Debug twig template

So where ever we need to change the html structure, we can identify the template file and can override by simply copy pasting the file within our theme template directory. For example if we need to alter the /page.html.twig then we need to place this in `/themes/my_sub_theme/templates/system/page.html.twig`.

Also we can make use of theme suggestions to override template only for specific page or region or block. For example, if we need to alter html template of navigation region then need to copy `/themes/bootstrap/templates/system/region.html.twig` to `/themes/my_sub_theme/templates/system/` and rename it as `region--navigation.html.twig` as per theme template suggestions.

In Drupal 8, twig template engine is being used as default template engine. That’s why template file follows the extension *.html.twig.

New to twig template then, these basics of twig will help you

Set and Print variables

Use set tag with in {% ... %} for assigning values. While printing variables can be modified using various filters followed by pipe( | ).

{% set foo = ‘bar’ %}
{{ foo }} {# outputs ‘bar’ #}
{{ foo|title }} {# outputs ‘Bar’ #}

{% set foo = {‘bar’: ‘foo’} %}
{{ foo.bar }} {# outputs ‘foo’ #}
{{ foo[‘bar’] }} {# outputs ‘foo’ #}

Control statements

Like variable assignment, control statements like if, elseif, else and for loops should be contained in {% … %} blocks.

{% if menus|length > 0 %}
  • {% for menu in menus %}
  • {{ menu.link }}
  • {% endfor %}

{% else %}

  • {{ login_menu.link }}

{% endif %}

Comments

Commenting can be done using {# … #} blocks.

{# Inline comment. #}
{# Multi line commenting.
    {% set foo = {‘bar’: ‘foo’} %}
    {{ foo.bar }}
#}

Debugging variables

For dumping any variable use dump() function.

{{ dump(foo) }}

For more reference on twig, please go through Twig for Template Designers.

Porting drupal 7 module to drupal 8 using Drupal Module Upgrader

We started to migrate our sites from drupal 7 to drupal 8, but we need our Drupal modules also to be ported from Drupal 7 to 8 and it’s time to port the same, Due to substantial changes in Drupal 8 from its previous versions, we "Drupal developers" find it hard to porting the modules from drupal 7 to drupal 8. This is mainly because Drupal 8 is object-oriented and much closer to a Model View Architecture(MVC), Drupal is no longer a Presentation Abstraction Control (PAC) architecture framework, Drupal follows the PSR-4 folder structure incompatible with Symfony component which Drupal 8 uses. To make our porting fast, we can use Drupal module upgrader.

Let's see what is a Drupal Module Upgrader?

Drupal Module Upgrader

Drupal Module Upgrader is a module which scans the source of a Drupal 7 module, and that flags any code that requires updating to Drupal 8 and it will attempt to *convert* the Drupal 7 code automatically to the Drupal 8 version using the relevant API changes which notice from Drupal List changes

 For a full description of the module, visit the project page:

          https://drupal.org/project/drupalmoduleupgrader

 

Installing the module

This module requires drush 8 or above, Assuming that the drush 8 installed in your system if it isn’t please visit how to install drush with the composer. Use the following Drush commands

drush dl drupalmoduleupgrader
cd modules/drupalmoduleupgrader
composer install

composer install

 

drush en drupalmoduleupgrader

Usage

  1. Place the Drupal 7 module which you wish to port into your Drupal 8 site's /modules directory. (not in sites/all/modules as like in drupal7)

  2. To scan code and get a report of code that needs updating and how to run the following Drush commands inside the Drupal 8 root directory:
drush dmu-analyze MODULE_NAME

dmu-analyze

      3. To attempt to upgrade your Drupal 7 module's code to Drupal 8 automatically, run the following inside the Drupal 8 root directory:

drush dmu-upgrade MODULE_NAME

dmu-upgrade

 

      4. The script will output a few lines as it attempts various conversions. Go into your modules/MODULE_NAME directory check out all of your new YAML files and such;)

Workarounds to @FIXME Tags

  • Enabling your drupal module can still throw off errors and/or give you a white screen death, even after the DMU-upgrade has executed successfully,  This is mainly because of the program while executing, skips call by references and minute changes like that. If you read your code after dmu-upgrade is done, you will see comment tags @FIXME. This is to indicate where the changes have to manually be done. Almost every change will be mentioned throughout the code and links to the corresponding change records are present in the html file generated by DMU-analyze

  • Only run dmu-clean after the code is bug-free and perfectly functional. Otherwise, the old code will be removed which had to be changed manually.

 

The Drupal Module Upgrader (DMU) module despite being in the development stages, saves developers a lot of time when upgrading modules to be compatible with Drupal 8.

 

If you need any help for Drupal Backup and Migrate, Feel free to Talk to Us for your Enterprises. 

Developing Drupal 8 sites in a smarter way - Drupal Console

I am sure You would have already started building sites on D8, by this time. And you would have noticed, how flexible and fast D8 is despite some struggles in the initial stage.

Tools to know about for Drupal 8

There are many supporting tools set to make D8 more faster & easier for developers. Drupal Module Upgrader - In short, we can port a d7 module to d8. Drush - Command line and scripting interface for Drupal Devel - Probably the single most important tool for module development, behind Drush.

And now I would like to share my knowledge on newly introduced and fascinated "Drupal Console". Wondering, what is Drupal Console? This is a command line interface. Wait, Again a CLI? Yes! Drupal Console project, like drush is headed towards full command-line abilities to control Drupal 8 site.  

So, How is console different from drush?

We have console newly introduced for only d8 which is inspired from symphony console, where as Drush is supported by older versions of drupal too.  So, now you might be thinking what is the need to both for drupal 8? Can’t we make use of only one CLI?

Its the features!

Drush:

  • Sync the file system using rsync
  • Import/Export databases.
  • Use drush aliases to manage environment

Drupal Console:

  • Generate code for Module, Content type, Controller, Entity, Rest resource, Service, Theme, Permissions etc.
  • Debug services, routes etc
  • Run unit tests.

They do have few in common too! Rebuilding cache, Managing of modules & configuration and generating own custom commands.

There are some discussions that happened on integrating console with drush, but this is not done. So, for time being, we have to use both drush and drupal console or may be choose one depending on your needs. Okay, Let’s try to integrate drupal console into our development workflow.

Installation of Drupal Console

I have used this guide to install and created a fresh drupal 8 instance. https://www.drupal.org/project/console (Installation and use)

# Create a new Drupal 8 project: 

drupal site:new drupal8.dev

This creates a new drupal 8 project instance.
Navigate to the site you have downloaded, and run following command.

# Install the new site:

drupal site:install

This installs your site instance.

No UI, Created a drupal 8 installation using CLI! Not only D8 installation, but drupal console aims at many other things to make developers work faster. Just start with typing the command and give your requirements as per the steps and your task is achieved in seconds!

Console Commands:

Lets dig out console by trying some interesting commands we might use often. Basic help command, to help us with instructions all the time.

drupal list

# Lists outs all the available commands

The other way round, I would also say drupal console as a learning tool for drupal 8. I am unaware of  how to create a Custom Form in D8. So I just used the following command.

drupal generate:form

You can now see, above command generates the structure required for the form with 3 methods getFormId(), buildForm(), submitForm(). And now it’s easy to create a Form. I have learnt a lot  from console in this way!

Let me share on few other things too i have learnt from Console.

Console for Developers

Assume you created a view with many fields, filters in some instance and now you want to use the same view in another site without creating from scratch.

drupal cev
# Exports a view into specified module.

drupal cev

Enter the module name [custom_module]:

> View to be exported [Archive]:

> test_view

Export view in module as an optional configuration (yes/no) [yes]:

>

Include view module dependencies in module info YAML file (yes/no) [yes]:
>

[+] The following module dependencies were included at
/var/www/html/d8/modules/custom/custom_module/custom_module.info.yml   [-] node   [-] user
commands.views.export.messages.view_exported
- modules/custom/custom_module/config/install/views.view.test_view.yml
- modules/custom/custom_module/config/install/node.type.article.yml

This will create views.view.test_view.yml, with any other dependent yml files under modules/custom/custom_module/config/optional/
If you choose optional as "no", In this case views.view.test_view.yml, with any other dependent yml files under modules/custom/custom_module/config/install/ and make sure you remove any other core yml files if exported along with this. You can still remove the config folder if you dont need it anymore! This way, You can now include this view into a module and reuse it in another site.

Connect/manage database using drupal console

drupal database:client

# This establishes a connection with the available database.

Connection: mysql -A --database=xxx --user=xxx --password=xxx --host=XXXX --port=XXXX

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is xxx
drupal database:drop

# drop all the tables in given database.
drupal database:dump

# dump the structure and contents of a database.

 

Console for Site Maintainers

Even the site maintainers can take an advantage of console to maintain the site in a smarter way.
We know drupal restricts the user to login after a couple of failed login attempts. So, to give access back to the user again, we have to clear those attempts from the database. Drupal console helps to do it in a single command.

drupal user:login:clear:attempts or drupal uscla

drupal uscla

> Enter User Id [1]

# Give the user Id.

> # This clears the failed login attempts of a particular user

Creating Custom Commands

Like drush, You can actually create custom commands too using Console.

drupal generate:command

Enter the module name [custom_module]:

>   Enter the Command name. [custom_module:default]:

> testcommand

Enter the Command Class. (Must end with the word 'Command'). [DefaultCommand]:

> TestCommand Is the command aware of the drupal site installation when executed?. (yes/no) [yes]:

>

Do you confirm generation? (yes/no) [yes]:

>

This will generate a Class at modules/custom/custom_module/src/Command/TestCommand.php with 2 methods.
configure --> Configuration settings of the command like name etc.
execute --> Process to be handled when the command is executed.

Now, to execute newly created custom command:

drupal testcommand

# This will do the process that is written in execute method.

Drupal console supports commands for a multisite installation too! We can use the drupal console commands on a multisite installation passing uri as argument.

We can also control the remote site from local with some initial setup(Check here)

Drupal Console as a debugging tool.

Debugging using Console, helps us know what actually is going on the site. Almost all the commands of drupal console have a debug option. Example:

drupal module:debug

#Lists out all the modules with status(enabled/disabled), Version of the module
drupal cron:debug

#Lists out all the modules implementing cron method.

I would say, Drupal console is the best smart tool that makes things more easier for a developer.

 


Reference:
https://drupalconsole.com/docs
https://events.drupal.org/neworleans2016/sessions/writing-command-line-tools-drupal-8-modules

 

 

How to define an Event, Dispatcher and Subscriber in Drupal 8?

As we all know Symfony Event Components are  included in Drupal8 core. In future versions of Drupal Core, Events are going to play a major role for sure. Let’s see how the Event component is going to help our Drupal Development. 

In one of the recent project, we got a tricky requirement in content authoring and publishing workflow. In specific, the Editor has to get a notification for reviewing, once a content author writes an article and saves it for reviewing. By using Events we can easily achieve this kind of  requirement. While ‘Content Author’ is saving content, we need to dispatch an Event, that has to be subscribed and a notification has to be sent to the respective ‘Editor’.

So here we are going to discuss about, how to define, dispatch and subscribe an event from our custom module. The following steps are involved: 

  1. How to define your own event in Drupal 8?
  2. How to dispatch the event in Drupal 8?
  3. How to subscribe an event in Drupal 8?

​First we are going to create .info.yml for our module called ‘example_events’ , which is example_events.info.yml

 

How to define your own Event in Drupal 8?

We have to define our event class under the ‘src/’ folder in your module root directory. Here we are defining our event class name as “ExampleEvent” and the file name as “src/ExampleEvent.php

While defining our event ExampleEvent, the class should be extended from

use Symfony\Component\EventDispatcher\Event

In the event class, you can define your own methods which can be accessed whenever dispatching the event or in subscriber call back. Here in our event class ExampleEvent, we use constructor to set the $referenceID, which can be accessed in Event Subscriber callback doSomeAction. Whenever the event ExampleEvent::SUBMIT is getting dispatched the $referenceID gets constructed.

 

How to dispatch the event in Drupal 8?

Event can be dispatched whenever you want like mentioned above.

In our “example_events” module, we have created a form[src/Form/DemoEventDispatchForm.php] and dispatched the event on Submit of the Form.

In the event dispatcher, first we need to load the Symfony event dispatcher object through services $dispatcher = \Drupal::service('event_dispatcher'); Then we should create our event class object. $event = new ExampleEvent($form_state->getValue('name')); Finally, we are going to dispatch the event through the dispatch method of the Symfony event component object $dispatcher by passing event name ExampleEvent::SUBMIT as first parameter and event object $event as the second parameter.

    $dispatcher = \Drupal::service('event_dispatcher');
    $event = new ExampleEvent($form_state->getValue('name'));
    $dispatcher->dispatch(ExampleEvent::SUBMIT, $event);
 

How to subscribe the events in Drupal 8?

There are a couple of steps involved in subscribing event in Drupal 8 as follows.

  1. Define your event Subscriber class that implements Symfony ‘EventSubscriberInterface’.
  2. Tag your Event Subscriber Class with ‘event_subscriber
 

1. Define your event Subscriber class that implements Symfony EventSubscriberInterface.

We should defining the Event Subscriber class under ‘ModuleRoot/src/EventSubscriber/’ directory, In our example, path will be,

example_events/src/EventSubscriber/ExampleEventSubScriber.php

In the EventSubscriber class ExampleEventSubScriber is implementing the interface EventSubscriberInterface from

 use Symfony\Component\EventDispatcher\EventSubscriberInterface;

In that we have to define the method public static function getSubscribedEvents() . This method will be returning a multi dimensional array containing the Event name ExampleEvent::SUBMIT and the Subscriber Callback doSomeAction with priority 800. In the Subscriber call back you can define your action which has to be taken whenever the event is getting dispatched. The event object will be passed to the Subscriber call back. Here our event object contains the referenceID.


In our ExampleEventSubScriber, we are subscribing one of the default event dispatched by Drupal Core which is ConfigEvents::SAVE defined by

use Drupal\Core\Config\ConfigEvents;

It will be dispatched , whenever you have any configuration change in Drupal. Please check the following video for the Demo.

 


 

2. Tag your Event Subscriber Class with event_subscriber

In your module.services.yml tag your event subscriber class as ‘event_subscriber’. Just like our event class. Tags indicate these service should be registered or for specific purpose, or that it belongs to a category. For more details on tags refer: Symfony documentation on service tags.

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


Conclusion:

Drupal 8 Events

Symfony Event Components are introduced in Drupal 8 Core. Still there is a long way to go. Entity APIs are still using hooks, which are likely to be available in Events on Drupal 9 version onwards. Anyway it’s good to learn and start using it because, its gives more ability to developer to develop things easier, especially in the era of real time updation.

10 Facts Media & Publishing Companies Should Know About Drupal To Enhance Digital Performance

Be it the most viewed’ Game of Thrones’ or the random ‘How to find your soulmate?’ article, all that matters at the end of the day is the ratings & revenue generated out of it.

So let’s cut to the chase!

How do you save millions for your company in the digital world using Drupal? Well, it’s with this total package of Drupal, being a one-stop shop. Let’s unfurl it.

1. Time is money! Manage your content better and save time.
Drupal is an open source CMS so with the community contributing modules, it reduces the effort in maintaining the web application itself. With a centralized content hub, your company with multiple child sites can share the same base for content development, which again saves time.

2. Ease out the process and reduce the effort
Let’s say, first thing in the morning you open your laptop and everything you need for the day is organized in your dashboard. That’s what Drupal does for easing out authoring experience with Editorial Dashboard. With the workflow tools, content tracking becomes simple. Now, you know how to convert this in the language of money.

3. Let’s talk business.
Drupal is highly flexible allowing easy placement of the revenue generating advertising spaces. Supporting your pay walls & online subscription management are just added advantages.

Monetise your assets

                                                                                                     Credit: Pixabay

4. Save & Earn through your assets!
You are rich when your website is rich. Video, audio and files have become the assets of a website. Drupal allows video, audio & file integration into the authoring workflow saving the authors from fragmented authoring. It will not only help you save but earn as a result of the rich media on your website.

5. Monetize your search.
Everyone is busy. Understanding this, Drupal provides enhanced search functionality getting you accurate search results saving you from hitting a wall. This reduces the development duration and saves you cost.

6. Know your audience & spend wisely.
Enhance your SEO weightage and SEO tagging with Drupal’s SEO analysis. Drupal’s market analysis modules aids in knowing the trend of your target market. To favour a personal touch of contents, browsing patterns of audience is powered by Drupal. Be smart in investing in your audience and save money.

7. Allow your money to grow from all mediums extensively.
In a world of 5 year olds running their fingers over an iphone & tablet, it’s no more about just the presence. It’s about the experience. Drupal being compatible to all devices from mobile phones to PCs, gives the customized reading experience by adjusting the screen to each device.

8. Score through social media!
Drupal makes social media integration hassle free. Newsletters and subscription management are not left out either so that you don’t miss out on your audience in any way. Reach out to your audience swiftly and save yourself from burning your pockets needlessly.

Know your audience

                                                                                                  Credit: Perspecsys

9. Scale up. Secure it. Finally speed it up.
Scalability is the biggest USP of Drupal saving you millions of dollars from getting stuck in the expansion phase. Spare your expense of site repair from crashing and have a good night’s sleep as Drupal offers top class security.

Rabbit or Hare? Rabbit of course! As no one wants to see that rolling ‘loading’ circle and for those expecting Usain Bolt’s performance in websites, Drupal comes in handy saving you from shedding those extra bucks into site maintenance. As for your users, well, they don’t get to see the rolling circle anymore.

10. Travel the world with less expense.
Get to include various languages for your website and save your cost as Drupal gives multi-lingual support. Let’s not ignore the audience belonging to different regions. Drupal also helps in region based customization of contents for multi site platforms.

If you want to execute this plan or if you plan on saving more then reach out to us. You can try our Drupal dev team for two weeks without any commitment or cost involved.

Setting up Vagrant on Windows for Drupal Development

Vagrant provides easy to configure, reproducible, and portable work environments built to improve productivity. It allows developers to build the virtualized environment once and keep sharing it for every case.

The file required to have a Vagrant machine i.e the Vagrantfile is written in Ruby, so if you are unfamiliar with it, using Vagrant can be a bit tricky. That’s where PuPHPet comes in. PuPHPet allows you to generate a package that contains all the needed code to create a virtual machine exactly as you decide on PuPHPet’s website.

Installing Vagrant on Windows environment is a multi-step process.

To install Vagrant, you need to download the appropriate version of Vagrant and VirtualBox packages.

STEP 1. Creating a location

Choose a directory where you would like your VM to be saved. This location is regardless of where you save your VM configuration and files. Create a folder where you decide to store your VM. In Windows, we can create a new folder in ‘C’ drive and name it ‘drupalvm’.

STEP 2. Installing VirtualBox

Next we need to download and install the latest version of VirtualBox for Windows from https://www.virtualbox.org/wiki/Downloads. Follow the normal installation procedure for Windows and VirtualBox should be up and running for you.

vagrant 1

 

STEP 3. Installing Vagrant

Download the Windows compatible Vagrant package from  https://www.vagrantup.com/downloads.html and follow the normal installation steps.
 

vagrant 3

 

STEP 4. Using PuPHPet to create your VM:

To create your VM configuration at PuPHPet, go to sitepoint.com/build-virtual-machines-easily-puphpet/. Here we will configure our virtual machine as per our need and customize it accordingly.

  • VM Settings: On the PuPHPet homepage, click on ‘Get started right away’. Next, you shall be directed to a page similar to the one below.

 

vagrant 5

 

  • Over here we shall select the Provider as ‘VirtualBox’ and our Distro as “Ubuntu Trusty 14.04 LTS x64”. You can select a distro as per your need and your system configurations. Leave the other details as default unless there is a need to change them.

  • Click next and move on to select the system packages. Over here select additional packages for your VM as per your need. Else, you can go on to the next step.

  • For a next few steps you can just go on clicking next leaving all the settings as default until you have to select the server.  

  • We would be using Apache as our server and so uncheck ‘Nginx’ and move next to select Apache.

vagrant 6

 

vagrant 7

 

  • Again over here we would the settings as default unless and otherwise required to be changed.
  • After this is done, you can further move on to the next few steps leaving the details as default. Next you can select the version of PHP you want to run. In my case, I would go ahead with PHP 5.6. Note that Drupal 8 needs PHP version 5.6 and up so select accordingly.
  • Next, instead of MariaDB we would be installing MySQL database. Go ahead and uncheck MariaDB to set up MySQL for the VM. You can configure MySQL as per your need. Select the MySQL version as 5.6. Further you can change the username and password if required.

vagrant 7

 

  • Further you can leave the configurations as they are for the next few steps. Next you should see a screen with the option to download the your customized archive.

vagrant 9

  • Go ahead and download the zipped folder by clicking ‘Download your custom..’. With this you are done with creating a customized VM using PuPHPet.

STEP 5. Setting up your VM:-

  • Once your download is complete, extract the folder to the location where you intend to setup your VM. In our case, we would extract the folder in C:/drupalvm created in step 1.

  • Once this is done, run your command prompt with admin privileges and point to the location of the folder with the ‘vagrantfile’. When you are inside this enter the following command in your command prompt.

vagrant up
 

  • This would set up vagrant on your system and is expect to take a while. Once this is done just type vagrant  in your command prompt. This shall start vagrant on your system. Further you can do a vagrant -v to check the version of vagrant installed.


STEP 6. Setting up the host:-

To create virtual hosts, we need to make changes to the host files on our system. Go to C:\windows\system32\drivers\etc\hosts and make changes to the host file using an editor with administrative privileges.

Go ahead and select a domain name for your Drupal project. You can use anything as  ‘drupal8.dev’ as my domain name. Accordingly add this line to the host file:

192.168.56.101   drupal8.dev

The IP address was chosen while creating our VM config file on PuPHPet. If you do not remember it now, you can find it by opening config.yaml using a text editor. The config.yaml file is located inside your puphpet folder, which you placed inside your VM folder earlier. We have just completed configuring a VM on our computer.

With this we are done with configuring a VM on our system. Go ahead and type the domain name - drupal8.dev  in your browser to access it.

You can learn more on Drupal development in our upcoming book co-authored by team at Valuebound.

Installing PhpStorm IDE for Drupal Development on Windows

Hey all, I’m a Drupal enthusiast, an engineer in the making from Goa College of Engineering with interests in web technologies and internet of things and currently doing internship in Valuebound. Stay tuned for my upcoming blogs.

In this blog, I would be installing PhpStorm IDE for Windows and configure it to work with Drupal. This post is for the benefit of all those who are new to Drupal and the learnings have been inspired from the book Drupal 8 Development: Beginner's Guide. There are many other alternatives to PhpStorm such as Eclipse, NetBeans, Komodo IDE etc. but of late PhpStorm has emerged as the preferred choice of the developers. There are quite a few advantages of using PhpStorm over other IDE’s. It’s Drupal friendly, and drupal development plugin comes pre-installed with PhpStorm. Although it’s a paid software you might qualify for free license if you are a student or working on open source projects.

Developing in Drupal involves a lot of testing and debugging at various stages. Using an IDE for the development work helps this task and is the most  preferred approach adopted, while developing in Drupal.

Before the PhpStorm installation, it is assumed that Drupal has been previously installed on your system. If not, it can be installed via XAMPP over the localhost or via Acquia Dev Desktop. Over here, we’ll be linking PhpStorm to our existing Drupal installation over XAMPP server.

So let’s dive in and start the process.

STEP 1:- Downloading PhpStorm IDE

PhpStorm is a product of JetBrains (previously IntelliJ).

  1. Visit the link www.jetbrains.com/phpstorm/download/ to get a list of all the versions of PhpStorm for different OS’s. As mentioned earlier, we are going to install PhpStorm for Windows, so go ahead and download the Windows compatible version of PhpStorm.

phpstorm_1

 

STEP 2:- Installing PhpStorm IDE

Once the download is complete, open up the file to start  the installation process. Go ahead and click next.

phpstorm_2

  • A. On the next screen, select the appropriate option for your system to create a desktop shortcut and choose the associations that you want PhpStorm to have. Selecting a particular association would enable the IDE to recognize and highlight the syntax of that option while using  that particular line of code in the IDE.

phpstorm_3

To keep things simple, let us select all the available associations. That will also help us in the long run. These associations can be created post the installation too, so you don’t have to worry much about them. 

  • B. Click Next, for a couple of more steps involved in the installation and finally, you should be having a window saying ‘Phpstorm has been installed on your computer’. Go ahead and run PhpStorm.

phpstorm_4

 

Congratulations!! You have successfully installed PhpStorm on your system.

STEP 3:- Linking PhpStorm to the existing Drupal installation

So now that PhpStorm has been installed, let us link our existing Drupal installation to it.

  • A. Run your newly installed PhpStorm IDE and you should see a screen similar to what is present below. Select the option ‘Create New Project’ and point to the location of your existing Drupal installation on the system. As mentioned, I’ve my Drupal installed over the XAMPP server. So I’ll be pointing out the project location to the location of existing Drupal installation over XAMPP. You can go ahead and point the location to where you have installed your Drupal.

phpstorm_5

 

  • B. On the next screen, you should see that PhpStorm recognizes that the directory is not empty. Go ahead and Click ‘Yes’ so that PhpStorm creates a project from the existing Drupal installation.

phpstorm_8

After all this is done, your PhpStorm IDE should be ready with all the existing Drupal installation files in the Projects window. Also as soon as the project is imported, the IDE starts indexing the project files on the system. Once this is done, you should see a screen similar to the one below.

phpstorm_10

 

As evident from the screen, PhpStorm has already recognized that the new project is a Drupal module and would ask you to enable Drupal support for the same. This option pops out on the top right corner of the screen.

phpstorm_11

  • C. Go ahead and click ‘Enable’ so that PhpStorm extends the Drupal support for the newly imported Drupal project. Next you would be asked to enable Drupal integration and to select the version of Drupal to extend support to. In my case, I’ve Drupal 8 installed on my XAMPP server so I will select version 8 on the pop up window.

 

phpstorm_12

 

  • D. Next, we will configure PhpStorm to follow the Drupal coding standards. For that - go to setting from file menu > Editor > PHP > Set from > Predefined style > Drupal. Most of the configurations would be handled by this. If not, you would have to configure it manually and cross check all the configurations.

phpstorm_13

 

Congratulations! The installation of PhpStorm and the linking of the existing Drupal project to PhpStorm is complete. You can now go ahead and develop, test or debug your Drupal modules, themes etc. right from your PhpStorm IDE.

You can learn more on Drupal development in our upcoming book co-authored by team at Valuebound.

Create custom Entity Type in Drupal8 for better content management

Entities were introduced from Drupal 7.  I would say in Drupal 8 , entities are essential part takers like node, users, files, images and comments, etc.. Still sometimes you need to create Drupal custom entities according to your requirements. From the experience of working with some of the top Media companies in the world, sometimes we need to create custom Drupal 8 entity types. Example like recently we got the requirement to create the entity for string the analytic data of the Articles. Why  we need to create  the custom drupal entity instead of using nodes  or exiting entities, because the client doesn’t want to show the data in content administration page (‘admin/content’). Still it should be able to manipulate the data and also easy to administrate with views, fields, etc. So finally we architect to create the custom Drupal 8 entity types.

Here in this tutorial, we will go through how to  create custom Entity type in Drupal 8. Entity is fully fieldable and uses most of the new entity concepts available in Drupal 8. We will be creating an entity type let’s say “inventory” and will also see how to create edit and delete

How to create a Drupal 8 Entity Type Programmatically?

So let’s create a module called “Manage Inventory” with the custom entity type ‘inventory’. And the details to create the module is explained in following steps,

Module Setup :

manage_inventory.info.yml

Routing :

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

manage_inventory.routing.yml

The route names for actions, defined in the 'link' section of the entity annotation must follow the right pattern.

manage_inventory.links.menu.yml

In addition of routing file, this replaces hook_menu for the module.

manage_inventory.links.action.yml

manage_inventory.links.task.yml

The "View/Edit/Delete" tabs will appear on the entity view page. The "Settings" tab will appear on the entity settings page.

Entity type classes

src/InventoryInterface.php

It’s better to provide an interface to define the public access to an entity. Here we invoked EntityOwnerInterface to get access to additional functionality.

src/Entity/Inventory.php

This file defines the Inventory entity class. The database schema is automatically determined from the definition of the base fields and here we can define the required fields for the content types. As mentioned in the routing section, the routes for the 'links' section must follow the right pattern. It is documented in the annotations section below.

Controllers

Let’s rewind. Until now we have seen routing, links and interface as well as Entity class. Once the entity type is created we need to provide an interface to the user for creating the entity.

Now let’s create form for creating entity.

src/Form/InventoryForm.php

Here we will define Entity form for adding and editing Inventory entity content. We can call this _entity_form defined in routing.

InventoryDeleteForm.php

Confirmation form while deleting the entity.

In above class we have submission handler for deleting any content and also for creating a log for the same.

src/Entity/Controller/InventoryListBuilder.php

Here we will be defining a listing page for the Entity type. In list we will be extending EntityListBuilder class to create list. We will be adding header with desired fields and later constructing row using rowBuilder method. Operation link will be added automatically from the parent class.

 

Field Settings

Till now we have seen,

  • How we can add routing
  • Creating Entity class for defining the entity with the default required field
  • Form for adding, editing content and deleting.

Now we will see how to add more fields from user interface. For that we need to define field settings class. So let’s create InventorySettingsForm.

src/Form/InventorySettingsForm.php

Access control handler

Entity type creation is done. Now we need to create access control handler for the same. With the implementation of EntityAccessControlHandler we will able to restrict the access of the content which we can manage from interface.

src/InventoryAccessControlHandler.php

After this, we need to register this entity type, which we will achieve by enabling the module. Incase you have enabled this module in the middle of this blog before creating Inventory class you will land up with error as  Drupal won’t have created the database table.

To overcome the error you can simply execute drush updatedb --entity-updates.When executing this command, Drupal will inform you that it found a new entity and that there's a pending update. After applying the pending update, you will be able to start using the new entity on your Drupal website!

 

 

Free Drupal Training by Valuebound, Bangalore on Drupal Global Training Days

We, at Valuebound, are excited to announce a hands on ‘Drupal-in-a-day' training session on the 10th of September ‘16, Friday. This is an initiative coordinated by the Drupal Association as a part of the  Global Training Days to introduce new people to the wonderful world of Drupal.

Come and be a part of world wide Drupal community! Make a live website yourself and know how Drupal can help you!

Difficulty Level: Introductory

Proposed Session: 

Get a leap on to the world of Drupal 8 . Learn about the main features and concepts of Drupal with live practice sessions. By the end of this training session you will know about the terminologies associated with Drupal and will be able to understand how Drupal sites are constructed. You will be equipped with the knowledge of how to differentiate and choose modules to get the functionality you want.

Duration: 1 day

Why is this workshop free?

Valuebound has been an active contributor to the Drupal Community and has achieved the second position worldwide through the same. This free event is part of our many more efforts to give back to the community.

Valuebound is solely dedicated in helping organizations and individuals to adopt Drupal in their operations in the most effective manner. We believe in giving result oriented training sessions which will equip you to build the perfect websites you visualize.

Who Should Attend?

  • PHP/Web developers: Give an edge to your career with a little more insight about how things work.
  • Students: Give a boost start to your IT career path as Drupal developer. Drupal is widely used by Fortune 500 companies, governments and startups.
  • Career switchers: Looking for the next opportunity to switch or learn what more  is there for you in Information Technologies? Come explore.
  • Project managers: Do you manage or are you considering Drupal projects? Know what you should know!
  • Decision makers: Evaluating Drupal to build your product on? Know why it’s the perfect fit.
  • Everyone, who is interested in knowing what Drupal is, evaluating or implementing Drupal.

Things you should know:

A little knowledge of what is a Content Management System would be great. Experience in using and creating websites using systems such as Wordpress, Joomla!, or HTML and CSS is a plus but  NOT a mandate. We encourage the newbies and shape up the Ninjas!

This session would present an outline of concepts of Drupal and not an in-depth course. It is awesome for folks  who are looking to get a head start or the ones looking for an edge in their career or profile.

By the end of the training you will be able to:

  • Build and make a basic Drupal site.
  • Select, install and configure modules and themes from Drupal.org
  • Create content and configure content types, create listings of content.
  • Manage user roles and accounts.
  • Manage aliases and URL paths.
  • Create blocks and place them in the layout

Bring along your laptop to make best use of this workshop.

How to register : The event is free but registration is mandatory. RSVP below to register.

RSVP

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