Creating a Module

Objectives
  • Create a new Drupal module
  • Make the module show up in the list of available modules
  • Let users install and uninstall the module

Where to install a Drupal module?

You should place your module in your Drupal project's /modules/ folder, commonly referred to as DRUPAL_ROOT/modules/.

   NOTE

   DO place your module folder under DRUPAL_ROOT/modules/
   Do NOT place it under DRUPAL_ROOT/core/modules/

By convention, the /modules folder should contain two subfolders:

  • DRUPAL_ROOT/modules/contrib/: contains modules downloaded from drupal.org
  • DRUPAL_ROOT/modules/custom/: contains your own custom modules

Activity

  • Create a folder named custom within your modules folder, if it doesn't exist yet.
  • Create a folder named demo within your /modules/custom/ folder.

The result should be the following folder: /DRUPAL_ROOT/modules/custom/

Hide hints
show hints

Making your module discoverable

Info File

As an absolute minimum, your new module must contain an info file which describes the module, its version, possible dependencies, and other information.

Its name must be YOUR_MODULE_NAME.info.yml, replacing YOUR_MODULE_NAME with the name of your module.

Note:

Every time you make a change to a yaml file such as the info file, you must clear your caches to force Drupal to take the changes into account.

Activity

The goal of this activity is to create and install a custom module. It doesn't do anything yet, other than allow itself to be installed, but that's ok. You will add more functionality later.

  • Create a file named demo.info.yml and place it in your /modules/custom/demo/ folder.
  • Add the following to the info file, and save:
name: "Demo"
description: "This module doesn't do much yet."
type: module
package: "Training"
core_version_requirement: ^9 || ^10

Reload the module page at Manage > Extend; your Demo module should be listed in the "Training" section, and you can install it.

If the module is not listed, you may need to clear the Drupal caches, either via Manage > Configuration > Development > Performance, via the Admin toolbar (the dropdown menu at the top), or via the command line using drush:

drush cr
Hide hints
show hints

Activity

  • Install your Demo module.
Hide hints
show hints

Troubleshooting

If your module is not listed:

  • Clear your caches
  • Verify the name and location of your module folder and of the info file
  • Ensure that the info file contains what is shown above
  • Ensure that the lines in the info file do not contain any leading spaces

Summary

  • Custom modules go in DRUPAL_ROOT/modules/custom/.
  • Contributed modules go in DRUPAL_ROOT/modules/contrib/.
  • A module needs an info file so Drupal can discover it.
  • You may need to clear your caches before Drupal detects new modules or changes to existing ones.