Create a simple module to use Drupal 8 Hook System

Submitted by editor on Fri, 07/08/2016 - 10:58
Question

What are the drupal hooks and how to use drupal hooks ?

Drupal 8 Hook System

Hooks allow modules to alter the drupal core behavior or another module. Hooks are discovered and called at specific times to alter or add to the base behavior or data (invoking the hook). Each hook has a name start with hook_ (Ex; hook_menu()). Your modules can also define their own hooks, in order to let other modules interact with them.

How to use drupal hooks ?

1. Create a custom module (See Create a simple module).
Hire module name is 'test'

2. Add a php file with .module extention at the root of the module called THEMODULENAME.module
Hire File name is test.module

3. Now you can implement any drupal 8 hook in this file

To implement a hook, you must replace hook_ by YourModuleName_. Ex hook_help() become test_help()

Example: Implement hool_help();

<?php
/**
 * Implements hook_help().
 *
 * Displays help and module information.
 *
 * @param path
 *   Which path of the site we're using to display help
 * @param arg
 *   Array that holds the current path as returned from arg() function
 */
function test_help($path, $arg) {
  switch ($path) {
    case "help.page.test":
      return '' . t("Hello, This is my first hook") . '';
      break;
  }
}

4. Then Visit /admin/help/test to Test your Hook
If you can see the message "Hello, This is my first hook", it's work.

 

More about Extending and altering Drupal : https://api.drupal.org/api/drupal/core%21core.api.php/group/extending/8.2.x

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.