How to create custom module in drupal 8

Submitted by admin@soz on Wed, 03/18/2020 - 22:52

This is a straightforward steps showing how to create custom module. For detail, you can read the source at the bottom.

1) Create module name under Modules folder

For example we create our module name as "example", so the folder should be like this

Module/Custom/Example

2) Create .info.yml file with note pad with this code - detail explain for .info.yml file

name: Drupal 8 custom module example
type: module
description: 'Example for Drupal 8 modules.'
package: Custom
version: 8.x
core: 8.x

Save it under Module/Custom/Example/example.info.yml

3) Creating .routing.yml with this code

example.my_page:
  path: '/mypage/page'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::myPage'
    _title: 'My first page in Drupal8'
  requirements: 
    _permission: 'access content'

Save it under Module/Custom/Example/example.routing.yml 

4) Create Route Controller Class

<?php
/**
 * @file
 * @author "your name"
 * Contains \Drupal\example\Controller\ExampleController.
 * Please place this file under your example(module_root_folder)/src/Controller/
 */
namespace Drupal\example\Controller;
/**
 * Provides 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;
  }
}
?>

Save it under Module/Custom/Example/src/Controller/ExampleController.php

5) Creating .module and hook_menu()

<?php
/**
 * @File
 * @author "your name"
 * Example custom module for Drupal 8.
 */

/**
 * Implementing hook_menu().
 */
function example_menu() {
  // The paths given here need to match the ones in example.routing.yml exactly.
  $items['/mypage/page'] = array(
    'title' => 'First page',
    'description' => 'This is a example page.',
    // The name of the route from example.routing.yml
    'route' => 'example.my_page',
  );
  return $items;
}

Save it under Module/Custom/Example/example.module

After that we can enable the module as regularly and start using it..

Check If the Module Functions

Visit the path you specified in your routing file - for this example, the path is: /mypage/page. If you get the ‘Page Not Found’ error, then clear the cache by navigating to admin->configuration->performance. Check again and it should function properly this time.


Source:-


YouTube: 


Related info:-

  1. How do I create table in custom module: https://drupal.stackexchange.com/questions/219580/how-do-i-create-table-in-custom-module

Custom module always use Hook