Drupal 8 Custom Block Module Dev

For those ready to move beyond a simple “Hello World” module, this post documents building a Drupal 8 module with a Giphy search form in a custom block. The form uses jQuery to request data from the Giphy API and display the results.

Drupal 8 module to demonstrate custom block creation with the following features:

  • configuration data that is passed into the modules js library
  • public API search using core jQuery functions
  • twig template for a front end Giphy search form
Source Code

Module Folder

To get started, create a folder for the module in either /modules/custom/ or /sites/all/modules/. The name of the module folder is typically the same as the name given to the module. In the case of this particular module, giphys is an appropriate name. For example:

# context is drupal project root

cd modules
mkdir custom
mkdir custom/giphys

Module Info File

An info.yml file is needed to store module metadata. Since the module machine name is giphys, the file will be named giphys.info.yml

# create the giphys.info.yml file

cd custom/giphys
touch giphys.info.yml

Here are the metadata contents of this file. Included is data to inform Drupal of the core compatibility, module dependencies and a description for the administration portal interface.

giphys.info.yml
name: Giphys
type: module
description: 'Giphys is a Giphy search block'
core: 8.x
package: Other
dependencies:
  - block

After saving giphys.info.yml, in Drupal, select the Extend menu, e.g., http://drupal.docker.localhost:8000/admin/modules. Giphys should be listed under Other:

Extend | Giphys

Module File

The giphys.module file is the entrypoint used to define help and theme hook functions that return respective data and paths. .module files should only contain functions that implement hooks.

# create the giphys.module file

touch giphys.module
giphys.module
<?php

/**
 * @file
 * Module file for giphys_module.
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 *
 * @see https://www.drupal.org/documentation/help-text-standards
 *
 * @see hook_help()
 */
function giphys_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.giphys':
      // Help text for the admin section, using the module name in the path.
      return t("This is help text created in giphys implementation of hook_help().");
  }
}

function giphys_theme($existing, $type, $theme, $path) {
  return [
    'giphys' => [
      'variables' => [
        'url' => 'http://example.com',
        'secret' => NULL
      ],
    ],
  ];
}

The next page covers twig templating for the HTML, module specific CSS and JavaScript asset management.


Published by

Jim Frenette

Web Developer - views here are my own except those taken from people more clever than me.

Loading Disqus Comments ...
Loading Facebook Comments ...