6 things to consider before you switch over to your new ECM system

Organized management and a good visual of your content gives you an edge over your competitors and this feeds the concern over when you should migrate to your new Enterprise Content Management (ECM) System . The whole process requires a huge capital investment and do not forget disrupting your business which can in turn spoil your customer’s digital experience. Before you go looking for a new ECM system to develop your new platform, you should consider an assessment of your current system that takes a comprehensive view of your current tools and processes. This assessment will cover a similar ground as the ECM system selection process and also gives the possibility that the best platform may be the one you already have.

If you go to a grocery store hungry, you will end up buying things you don’t actually need. Most smart people avoid this by making a list of essentials. When it comes to selecting a new ECM system, documenting your needs is an absolute necessity. Comparing your existing ECM system to the functionalities  you are hoping for, is a matter of magnitude. By considering each area carefully, your organization can make the best strategic decision possible and get the most value from the ECM system you implement. Now assessing the implementation is the matter of measuring this magnitude which we cover in the following six points:

  1. Integration of ECM system with your Business process

    The main aim of integrating your business with an ECM system would be to content-enable the business applications so that the latest and most accurate information is readily available.

    Unstructured content can be scattered across various repositories which can happen due to individual applications having their own stores for related information.

    Significant cost savings can be achieved when the core business applications are organized and content enabled. This improves efficiency(Fig 1.1) and reduces reliance on paper and also lowers physical storage.

    Business drivers for document and record management

    Fig 1.1: The most significant business drivers for document and records management (Source: AIIM, State of the ECM Industry 2011)

    Although the ability to organize and structure pages is not required now, it might be needed in future. Always look out for CMS which do not allow flexibility for such core tasks.

  2. Core ECM Capabilities

    As the company grows, so does the variety of content that needs to be archived and content that needs to be disposed off. A good ECM system should be able to manage the entire lifecycle of various content types and support other processes like search, retention and rendering associated with the content types and also let you define each step of the content’s lifecycle.

    Records Management and retention policies helps control the creation, classification, declaration, retention, and destruction of content and records, resulting in improved compliance, minimum litigation risk, and lower storage costs.

    Basic functionalities to consider include:

    • Search- full-text search, filtered search results for end-users to quickly find what they have authorized access to, and advanced search capabilities like custom search forms and metadata search.

    • Metadata, Classification and Taxonomies- Support for automated, manual and inherited metadata values on all types of content and classification of content based on these values.

    • Versioning-automatic tracking and storage of each file version along with auditing, archiving and the ability to revert to a previous version of a document if needed.  

    • Rendition support-the ability to automatically generate content in other formats (PDF, XML, HTML).

    • Compound document support – to allow smaller documents to be incorporated within a master or parent document.

  3. Ease of Access (multi-channel content creation & consumption)

    A good ECM system allows your employees or users to access information from various devices. These days it is important to make your information accessible through mobile devices. Whether it is for intranet, ethernet or mix of both, access to content in this context adds significant value.

    A CMS implementation has three primary requirements: developer’s needs, user experience and the content author’s needs to maintain the user experience.

    The user’s and developer’s needs usually become the focus of an ECM System implementation, but the process doesn't end when it goes live.

  4. Content Authoring Workflow

    The CMS of choice should also have expandable workflow capacity to meet the future needs of your business. Analyzing the workflow of your organization helps you select a better suited ECM System.

    If your authors face difficulty  working with your new ECM System, it’s implementation might not serve your purpose well. A discontent from the author community will affect the business as your system is starved of new content  and you might go through another cycle of a new CMS implementation.

    Encourage author adoption of the new ECM System by both training and considering various functionalities of your new ECM System that your authors require.

    These functionalities can be types of content that can be submitted, provision of author tools (eg: SEO, spell check, standard taxonomies, compliance tools, auto-complete of metadata items), a suitable permission model to hide irrelevant features from the author etc.

  5. Enterprise-Class Capabilities

    The ability of an ECM System to grow and adapt to your business’s growing needs in a way that it does not bring up limitations is one critical factor to be considered. Also, it should not add significant support costs in  future.

    You new ECM system is going to be the information backbone of your company and should meet certain requirements:

    • Scalability- It should be able to scale thousands of users and billions of content types and also manage the lifecycle of these information efficiently.

    • Security- Admin’s ability to define access to various types of information based on the type of user, different groups across the organization or an end user. A good ECM System will have data encryption and restrictions on database access to provide optimum level of security.

    • Managing,Auditing and Reporting- A unified administration has better manageability and lower costs. Having a lone platform that allows an admin to manage all the information, services and reports and logs from a single console reduces staffing requirements and improves compliance by eliminating the creation and enforcement of redundant policies and procedures.

    • Multilingual support- To reach the world wide audience an organization requires localization support for a number of languages and the ability to adapt to different time zones.

    • Service Oriented Architecture (SOA)- The ECM System’s ability to integrate with various types of systems is essential to ensure that your content is readily available across the enterprise.

  6. Strength of Vendor

    You ECM system provider should have the commitment, longevity and the financial strength to be your business partner for years to come. While evaluation a suitable vendor, you should consider:

    • The available educational and training materials
    • Training personnel
    • Availability of global tech support.
    • Ability of address issues in a timely manner.
    • Availability of other implementation partners and subject matter experts globally.

Conclusion

Whether you are considering an upgrade to your current ECM System, a replacement of an older system or the purchase of a completely new ECM System, there are many important criteria involved in electing the best content management system suited for your organization. Apart from the 6 points mentioned here there might be other requirements which will build your list further. We hope you find this useful and consider Valuebound to build your future. More information on our work is available at Valuebound.

Valuebound sponsoring BAD Camp 2016

BADCamp is a Drupal conference for the people. It’s an annual celebration of open-source software in Berkeley CA. We at Valuebound, are thrilled to be sponsoring BADCamp this year, to be held on October 20-23. We are excited to welcome more people be a part of BADCamp inspiring sessions and community!

 

Badcamp VB

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.

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