drupal

Creating Drupal 8.x modules

Date: Posted by: Karthick In: Drupal

drupalA simple Hello, Drupal example

To Start Module follow the below steps to enable errors: Go to settings.php

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
    //Note:  Do not include the opening and closing PHP tags when you copy this code
?>

In addition, navigate to Administration→ Configuration→ Development → logging and errors and select “All messages”. (This sets $conf['error_level'] = 2; .)

Go to: php.ini

set error reporting to E_ALL | E_STRICT

Start Your Module by

Create a folder for your module:

modules/hello_drupal (or) sites/all/modules/hello_drupal

Create a new ‘.YML’ File for  your module’s root folder:

hello_drupal.info.yml

name: Hello Drupal Module
description: Creates a page showing "Hello Drupal".
package: Custom
type: module
version: 1.0
core: 8.x

 Adding a basic controller:

This controller file will return our “Hello, Drupal!” message when it is invoked by the routing system.

  • Within your module folder, create a sub-folder called src
  • go to src folder and create a sub-folder called Controller
  • create a new file, called HelloController.php

<?php
/**
* @file
* Contains \Drupal\hello_drupal\Controller\HelloController.
*/
namespace Drupal\hello_drupal\Controller;
class HelloController {
public function content() {
return array(
'#type' => 'markup',
'#markup' => t('Hello, Drupal!'),
);
}
}

 Add a routing file:

  • Open hello_drupal.routing.yml

add the following to it:


hello.content:
path: '/hello'
defaults:
_controller: '\Drupal\hello_drupal\Controller\HelloController::content'
_title: 'Hello World'
requirements:
_permission: 'access content'

Next clear your site’s cache

Add a menu link:

Now in the root folder of your module, create a new file, called hello_drupal.links.menu.yml and add the following to it:


hello.admin:
title: 'Hello module settings'
description: 'example of how to make an admin settings page link'
parent: system.admin_config_development
route_name: hello.content
weight: 100

This will add a link within the administration pages of your site under the Configuration tab in the Development section.

Lets try the new link into your page and comment below if you have a doubt.

Drupal_Module

377 Views

Top