Member-only story

How to Create a Custom Hook In Drupal

And use it in your custom module

Sergio Guardiola Herrador
1 min readOct 12, 2023
Photo by Steve Johnson on Unsplash

In Drupal, a “hook” is a predefined function used by developers to customise and extend the CMS by responding to specific events or interactions, allowing for modular and flexible website development without modifying core code.

Creating a hook in your custom module is very simple. All you need to do is adding something like this and sending the variable for other modules to be able to modify it:

// Allow other modules to alter status.
\Drupal::moduleHandler()->invokeAll('content_translation_alter_status', [&$status]);

In this case, I needed to be able to alter the values in $status variable, that’s why I submitted patch to Drupal.org: https://www.drupal.org/project/drupal/issues/3393739

And this is how I use it in my custom module (replace hook with your custom module name):

function hook_content_translation_alter_status(&$status) {
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
$moderation_state = $node->get('moderation_state')->getString();
$moderation_state = str_replace('_', ' ', $moderation_state);
$status['data']["#template"] = ucfirst($moderation_state);
return $status;
}
}

👉 Find out more about me here: https://sergioguardiola.net 🔥

--

--

Sergio Guardiola Herrador
Sergio Guardiola Herrador

Written by Sergio Guardiola Herrador

I write articles in English and Spanish, mostly about programming, technology, travel, money, investing. You can find me here: https://sergioguardiola.net

No responses yet