Drupal – Create a Custom Hook for Other Modules to Use

In this example, we’ll explore how to make a custom hook with our module so that other modules may use it.

For example, say we were implementing hook_entity_delete() to display a custom message whenever an entity was deleted. But before we display the message, we want to allow other modules to modify the message if they want. We would do that by ‘creating’ a custom hook by using module_invoke_all(), like so:

In the code example below, we’ll ‘create’ a hook called: hook_change_my_entity_delete_message()

/**
 * Implements hook_entity_delete().
 */
function MY_MODULE_entity_delete($entity, $type) {
  
  // Create our message variables.
  $variables = array('msg' => 'foo');

  // Make sure at least one module implements our hook.
  if (sizeof(module_implements('change_my_entity_delete_message')) > 0) {
    // Call all modules that implement the hook, and let them make changes to $variables.
    $variables = module_invoke_all('change_my_entity_delete_message', $variables);
  }

  // Display the message.
  drupal_set_message($variables['msg']);
}

Now if another module wanted to implement this hook and change the message, they could do that like so:

/**
 * Implements hook_change_my_entity_delete_message().
*/
function SOME_OTHER_MODULE_change_my_entity_delete_message ($variables) {
  $variables['msg'] = 'bar';
  return $variables;
}

Now when an entity is deleted, our implementation of hook_entity_delete will get called and get ready to display the message, then call any module that implements hook_change_my_entity_delete_message(), then return and print out $variables[‘msg’].

Which in this case the drupal_set_message would display: bar

Advertisements

One thought on “Drupal – Create a Custom Hook for Other Modules to Use

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

WordPress.com.

Up ↑

%d bloggers like this: