Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Modules and Hooks

Hooks and Event Subscribers

Change Drupal behaviour without touching core: hook implementations, alter hooks, OOP hooks in Drupal 11, event subscribers and a runnable hook-system stand-in.

Drupal is designed to be extended, not edited. The two main ways a module reacts to what the system is doing are hooks and events. Hooks are the traditional Drupal mechanism: Drupal announces "I am about to save a node" and calls every module that has a function with the right name. Events are the Symfony mechanism used by newer subsystems: code dispatches an event object and registered subscribers receive it.

Drupal cannot run on this site, so the PHP is read-only. The TryIt blocks build a small hook and event system in JavaScript, which is the same idea in miniature.

How hooks work

A hook is a naming convention. To implement hook_node_presave() in a module called tutorial_notes, you define tutorial_notes_node_presave() in tutorial_notes.module. Drupal asks the module handler for all implementations and calls each in module weight order.

PHP
<?php

use Drupal\Core\Entity\EntityInterface;
use Drupal\node\NodeInterface;

/**
 * Implements hook_node_presave().
 */
function tutorial_notes_node_presave(NodeInterface $node) {
  if ($node->bundle() === 'article' && $node->getTitle() !== trim($node->getTitle())) {
    $node->setTitle(trim($node->getTitle()));
  }
}

/**
 * Implements hook_entity_insert().
 */
function tutorial_notes_entity_insert(EntityInterface $entity) {
  \Drupal::logger('tutorial_notes')->info('Created @type @id', [
    '@type' => $entity->getEntityTypeId(),
    '@id' => $entity->id(),
  ]);
}

Useful hooks you will meet constantly:

  • Entities: hook_entity_presave, hook_entity_insert, hook_entity_update, hook_entity_delete, hook_ENTITY_TYPE_view and per-type variants such as hook_node_presave.
  • Pages and themes: hook_page_attachments, hook_theme, hook_preprocess_HOOK, hook_theme_suggestions_HOOK_alter.
  • Forms: hook_form_alter, hook_form_FORM_ID_alter.
  • Menus and routes: hook_menu_links_discovered_alter, hook_link_alter.
  • Housekeeping: hook_cron, hook_install, hook_uninstall, hook_update_N, hook_mail, hook_help.
Node.js Stand-in: a hook system

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Alter hooks

An alter hook gives you a chance to change something another module built. The data is passed by reference. The best-known is hook_form_alter:

PHP
use Drupal\Core\Form\FormStateInterface;

function tutorial_notes_form_node_article_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['title']['widget'][0]['value']['#description'] = t('Keep titles under 60 characters.');
  $form['#validate'][] = 'tutorial_notes_article_title_validate';
}

function tutorial_notes_article_title_validate(array &$form, FormStateInterface $form_state) {
  $title = $form_state->getValue(['title', 0, 'value']);
  if (mb_strlen($title) > 60) {
    $form_state->setErrorByName('title', t('The title is too long.'));
  }
}

Other common alters are hook_menu_local_tasks_alter, hook_views_query_alter, hook_block_view_alter, hook_library_info_alter and hook_css_alter.

Object-oriented hooks (Drupal 11)

Since Drupal 11.1 a hook can be a method with an attribute, in a class under src/Hook/, with no .module function:

PHP
<?php

namespace Drupal\tutorial_notes\Hook;

use Drupal\Core\Hook\Attribute\Hook;
use Drupal\node\NodeInterface;

class NoteHooks {

  #[Hook('node_presave')]
  public function nodePresave(NodeInterface $node): void {
    $node->setTitle(trim($node->getTitle()));
  }

}

The class is a service, so constructor injection works. Procedural hooks in .module files still work and are common in existing code, so you need to read both styles.

Events and subscribers

Newer APIs use Symfony's event dispatcher. You write a subscriber class, tag it in services.yml and subscribe to event names:

YAML
services:
  tutorial_notes.request_subscriber:
    class: Drupal\tutorial_notes\EventSubscriber\MaintenanceBannerSubscriber
    arguments: ['@current_user']
    tags:
      - { name: event_subscriber }
PHP
<?php

namespace Drupal\tutorial_notes\EventSubscriber;

use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class MaintenanceBannerSubscriber implements EventSubscriberInterface {

  public function __construct(protected AccountProxyInterface $currentUser) {}

  public static function getSubscribedEvents(): array {
    return [KernelEvents::RESPONSE => ['onResponse', -10]];
  }

  public function onResponse(ResponseEvent $event): void {
    $event->getResponse()->headers->set('X-Tutorial-Notes', 'active');
  }

}

The number is the priority: higher runs earlier. Other events you may use: KernelEvents::REQUEST (redirects, language), KernelEvents::EXCEPTION, RoutingEvents::ALTER (change routes), ConfigEvents::SAVE, and entity events in contributed modules such as Rules or Webform.

Node.js Stand-in: events with priorities

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Hooks or events?

  • Use the hook or event the API documents; you rarely have a choice. Entities, forms, themes and render use hooks; request handling, routing and config use events.
  • Hooks are discovered by naming; events and OOP hooks are explicit and easier to test.
  • Both can run on every request, so keep them quick and avoid database queries in hooks such as hook_page_attachments.
  • Find hooks in *.api.php files in core, or use drush generate hook.

Custom hooks

Your module can define its own hook so others can extend it:

PHP
\Drupal::moduleHandler()->alter('tutorial_notes_summary', $summary, $note);

Document it in tutorial_notes.api.php. Other modules implement hook_tutorial_notes_summary_alter(&$summary, $note).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the function name for hook_node_presave in a module called notes?

    Replace the word hook with the module machine name.
  2. 2. How do you register an event subscriber?

    The tag tells Drupal to collect the class as a subscriber.
  3. 3. What does an alter hook receive?

    Alter hooks take data by reference and modify it in place.
  4. 4. Which event subscriber priority runs first?

    Higher priority numbers are called earlier.

Summary

  • A hook is a function named MODULE_hookname; alter hooks change data by reference.
  • Drupal 11 also allows hooks as attributed methods in classes.
  • Events use subscriber classes tagged event_subscriber, with priorities.
  • Keep hooks and subscribers fast; they can run on every request.
  • Look in *.api.php and use drush generate for the exact signature.

Next: Services and Dependency Injection