How to Make Custom Module in Drupal 8

create drupal module

In this article, we will discuss about drupal 8 module development in drupal CMS. Drupal 8 is the latest version of Drupal cms and completely object oriented with complex coding structure. Keeping this in mind, we have written this article which helps drupal developers to create a custom module in simple steps.

Here are the steps to create custom module in Drupal 8:-

  1. Create your own module with standard info.yml file.

    In drupal 8, this is the only required file for your module though it is not enough to get the job done. Unlike Drupal 7, info files are now formatted in YML format. In this case, we created a module folder called 'test_module' and test_module.info.yml with following code:-
     

    name: Test Module
    description: An experimental module to test module creation
    package: Test
    type: module
    version: 1.0
    core: 8.x

  2. Create test_module.module file with the following code.

    .module file can be used for variety of things.. Here we are using it to create a help menu to be displayed in Drupal help section. If you would like to create a block with custom module, please checkout - how to create custom block in drupal 8. hook_menu() is no longer exist in Drupal 8, so we are using RouteMatchInterface class in the code.

    <?php

    /**
     * @file
     * Defines simple help link.
     */

    use Drupal\Core\Routing\RouteMatchInterface;

    /**
     * Implements hook_help().
     */
    function test_module_help($route_name, RouteMatchInterface $route_match) {
      switch ($route_name) {
        case 'help.page.test_module':
          $output = '';
          $output .= '<h3>' . t('About') . '</h3>';
          $output .= '<p>' . t('This module is nothing but teaching how to create custom modules in Drupal 8.').'</p>';
          return $output;
      }
    }

  3. Enable the module.

    We're done with our custom module. Please go to '/admin/modules' and enable the module 'Test module'. Once enabled please browse 'Help' section by visiting 'admin/help'. Now you should see a link 'Test module' and it would give you an overview(as written in hook_help()) of our custom module.

 

drupal 8 module development

 

These are the important steps to create a basic module in Drupal 8. Please note that it just gives you an idea about basic module development in Drupal 8. Once you understand Drupal 8 module structure, you will be able to achieve what you would like to implement using your custom module.

Hope you found this article useful. Please post your comments/thoughts in the comment section below.