[Drupal] How to create a custom module in Drupal 8

December 11, 2014 - 12:11

Drupal 8 is the latest version of Drupal. There are significant differences between Drupal 8 and Drupal 7. Firstly, Drupal 8 requires the latest version of php5 to run. Drupal 8 uses a PHP framework called Symphony, which relies heavily on OOP. Another major change in Drupal 8 is the folder structure. In Drupal 8, all core modules are placed within core/ and all other modules are placed in root modules folder. Moreover, there are changes in the way modules are created. Read on to know how to create a custom module in Drupal 8.

A Drupal8 custom module consists of three basic files:

  • module_name.info.yml holds the module info
  • module_name.routing.yml file for holding ‘routing’ info or hook_menu
  • module_name_Controller.php for controller classes and its callbacks.

In Drupal 8, the info file (module name.info.yml) would be the same as Drupal7 :


    name: Sample
    description: 'An example module'
    core: 8.x
    version: 8.x.1.0
    type: module
    package: Custom
    

Now, we require another yml file called (module name.routing.yml). This is for the hook_menu, and this should be in yml syntax with file name (module name.routing.yml) file in the root of the module folder :


    sample.main:
      path: '/sample'    
      defaults:
        _content: '\Drupal\sample\Controller\SampleController::samplePage'    
        _title: 'Sample'
      requirements:
        _permission: 'access administration pages'
    

Our next step is to create the Controller class and method that defines our callback. Create a new file called 'Controller.php' in module (src/Controller/Controller.php)


     'Hello World!',
        );
        return $output;
      }
    }
    ?>

   
    

In this file, our new controller extends the ControllerBase class. ControllerBase was created to hide a lot of boilerplate code that applies to most page-based controllers.

The samplePage() function returns a render array that contains our 'Hello World!' text.

At this point, enabling the module and visiting the /sample should now show a page titled 'Sample' with the contents of 'Hello World'.

If you need any functionality in this hello page or module, you should create a hello.module function and write functions & hooks inside the file.

reference

Get Drupal updates straight to your inbox

To prevent automated spam submissions leave this field empty.

Post your comments / questions