How to Create Custom field in Drupal 8 (Part -1)

In a recent project we had to create a section that is having range  with the select list for the unit. It had to be usable in different sections of the layout and work the same. For this we came up with a pretty nifty (we think) solution of creating a custom field that solved this particular problem for us. I will walk you through how to create a custom field/widget/formatter for Drupal 8. There are Drupal console commands for generating boilerplate code for this…

To Create Custom field we need to create 

  1. Field Type
  2. Field Widget
  3. Field Formatter


This is the folder structure for creating the same

Temperature Range

  • temperature_range.info.yml
  • src/
    • Plugin/
      • Field/
        • FieldType/
          • TemperatureRangeItem.php
        • FieldFormatter/
          • TemperatureRangeFormatter.php
        • FieldWidget
          • TemperatureRangeWidget.php

Field Type creation
First, we need to create our own custom module, we can use drupal console for creating new module, then 

The namespace of that class should be \Drupal\MODULE_NAME\Plugin\Field\FieldType
In our example \Drupal\temperature_range\Plugin\Field\FieldType\BazItem

To create a field type, you need a class with the FieldType annotation.

The annotation above the class, within the doc comment, should include a unique id, and a label.

Then provide a schema for the field. This will be the properties that we have created above.

Then provide the field item’s properties and this will be the properties which we created

In the forthcoming blog, we will see how to create field widget and field formatter which both will complete the custom field creation

Get your Drupal8 Development platform ready with Drush8!

As we all know, we need Drush8 for our Drupal8 development platform. I have tried installing Drush 8 using composer, but sometimes it turns out to be a disaster, especially when you try to install Drush 8 on the Digital Ocean Droplet having Ubuntu 16.04.

I have faced the same issue in the last few months to get the Drupal8 development platform ready with Drush8. So I have decided to find a solution to fix that forever. Well, finally found one which are the following lines of commands.

cd  ~
php -r "readfile('http://files.drush.org/drush.phar');" > drush
chmod +x drush
sudo mv drush /usr/bin
drush init

If you are still facing any issue, please leave a comment, We will help you out to get your platform ready with Drush8.

When should your Digital Transformation journey include a Multilingual Website?

When you have a media website with visitors from a language background other than your default, it’s best to switch to a multilingual website to ensure you do not lose your business and have a continuous growth.   

Do you have website visitors from non-English speaking countries?

Do you know there are more than 40 Million native Spanish speakers in the USA out of which 72% prefer websites in their native language?  Then there is Chinese, French and so on to name some of the most popular language based users which add up to 75% with English being only one-fourth. What are you doing to target these 75%? Why not zoom in on the less focused and make loyal customers out of them? To them, you are not just another digital media company delivering the same old content from places they don’t relate to, to them you are more of their national daily.

How do you cater to your web visitors if they are non-English Speaking users?

Do you display the content in the same default language? You might have translated the content but then there is page layout, word spacing and expansion and contraction per language requires you to have a site which can handle such flexibility

Are you equipped to make changes for every new language that you add to your list?

Adding a new language to your website comes with challenges. Are you looking for answers that handle the complexity of language translation requirements? Are you thinking how to organize your content? You have blogs, headlines which link other articles together, out of that what all can be translated and shown to the users? All of it or only the basic content?

Will it affect to have an interface that speaks the language of your target market?

Of course, your website does not target people of one language. And having a monolingual website gives you a limited audience, which is a loss for your business. Hence it is about time for you to customize your website to accommodate new languages

What factors are keeping you from growing your business?

One aspect of getting feedback or suggestions is through forms. Forms are a critical part of your website through which users can connect with you, having a form page that displays only in one language is going to hamper business for you. It is, therefore, important that the forms are easy to use and presented in the user's’ native language.

With the boom of devices and screens available to consumers, people now have unhindered access to every content they want, the way they want, with a special focus on their favorite brands and sites. This sets the standard higher and creates a necessity for the brands to deliver the best of experiences — with no regards whatsoever to the device, size, screen, mobility or any other point of contact, here the experience matters because your customer’s expectation is high. As a matter of fact, the standard keeps getting higher and higher that it because some of the brands like yours have been setting an example for the others to follow.

Why do you need Multilingualism?

With the internet crossing the 10k day this past week, from the time it was invented the world of publication likewise has undergone drastic changes, we swipe our finger to turn the next page of a book and scroll the site to take a look at the news headlines. It is no more limited to one part of the world and people from all regions and languages have access to what you write.

Writing is digitally accessible and digitally published. Businesses are gearing up to reach and penetrate through every corner of the world and here is where localization comes into the picture. Your diversified and multilingual global society has immensely added to the importance of translation in the publishing industry. Media and publication industry needs to reach out to various geographical regions having its own distinct language.

The world of media and publishing witness rapid changes and is regularly making way for a broader audience. Most multinational media companies are already on the path of this transition to secure an international foothold. Whether you choose to go down this path now or later is the only question.

The team at Valuebound has experience of working on high-traffic multilingual Drupal websites. If you are still wondering if Multilingual is the right way to go, we can help you make this decision.

References -

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.

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