‘Drupal 8 Creating custom module steps
Costume Module file structure (My Drupal version 8.1.2)
1. Create a folder under ‘/modules/’ for this explanation I am creating a ‘example’ (this is our module folder) folder inside module folder
2. Create module info file ‘example.info.yml’ inside example folder
name: Drupal 8 custom module example type: module description: 'Example for Drupal 8 modules.' package: Custom version: 8.x core: 8.x
3. Create example.module inside example folder
<?php /** * @File * Example custom module for Drupal 8. */ /** * Implementing hook_menu(). */ function example_menu() { // The paths '/examp' should be same in example.routing.yml. $items['/examp'] = array( 'title' => 'Example page', 'description' => 'This is a example page from example module.', // The name of the route from example.routing.yml 'route' => 'example.my_page', ); return $items; }
4. Create example.routing.yml in example folder
example.my_page: path: '/examp' defaults: _controller: '\Drupal\example\Controller\ExampleController::myPage' _title: 'My first page in Drupal8' requirements: _permission: 'access content'
The path: ‘/examp’ begin with 2 space catheters. Here we are defining the end point (http://localhost/examp [ I am using ‘localhost’ for development])
5. Create controller:- for creating controller first we need to create an ‘src’ folder inside example folder inside src folder create a ‘Controller’ folder and inside it create ExampleController.php
the controller full path will be like this ‘modules/example/src/Controller/ExampleController.php’
<?php /** * @file */ namespace Drupal\example\Controller; /** * Route responses for the Example module. */ class ExampleController { /** * Returns a simple page. * * @return array * A simple renderable array. */ public function myPage() { $element = array( '#markup' => 'Hello world!', ); return $element; } } ?>
6. Install the new module from admin
7. Open your favorite internet browser hit your example URL (in my case : http://localhost/examp) you can see the generated page
GitHub : https://github.com/bikeshm/drupal-8-module-sample1
Check how to create a custom block : https://wiki.workassis.com/drupal-8-creating-custom-block-from-scratch/