10

I posted a question here, which had one suggestion, but no answer. Does anyone have any advise on how to implement a custom hook in Drupal 8 which will allow other modules to update a table of contents which is created by a parent module? The table of contents will be an unordered list.

  • 2
    Have a look at the section under "To define a hook:" here, does that help? – Clive May 14 '16 at 13:13
  • Only partially. This explains how to create a hook for the child function to use, but nothing on how the parent module renders the content. Does the parent use a controller to add content to, say, $output['table_of_contents'] and then the parent's hook appends the data that is returned from the child, to this array? – Kevin Nowaczyk May 14 '16 at 13:24
  • 2
    @KevinNowaczyk it depends on the purpose of the hook. A hook is not specific for rendering, but can be used for it. If you want to create a custom hook to provide content and you invoke the hook at the place you need the content, it will work. And because the hook is custom and new to your function, you have to define how the hook should provide its results. Then if you invoke the hook during your parent render function you can receive the results in a usable format. – Neograph734 May 14 '16 at 14:15
8

This section resides in a controller in the parent module:

$plugin_items = [];
// Call modules that implement the hook, and let them add items.
\Drupal::moduleHandler()->alter('flot_examples_toc', $plugin_items);
if (count($plugin_items > 0)) {
  $output['plugins'] = [
    '#title' => 'Plugins',
    '#theme' => 'item_list',
    '#items' => $plugin_items,
  ];
}

And this resides in the child [module].module file.

use Drupal\Core\Url;

function mymodule_flot_examples_toc_alter(&$item_list) {
  $options = [
    ':one' => Url::fromRoute('flot_spider_examples.example')->toString(),
  ];
  $item_list[] = t('<a href=":one">Spider Chart</a> (with spider plugin)', $options);
}

The parent creates an array and passes it to the children by reference. They can alter the array by adding elements to it. The parent then adds it to the render array.

3

Just for simplicity sake if you want to create and use a custom hook in drupal 8 for other developers to use

first to help others define the use of your hook in mymodule.api.php file this hook can act on anything required.

example:

 // my hook 
 function hook_mymodule_alter_something(array &$data) {
   // here others will make a module that will call this to alter "$data"
 }

then when needed in your module.

 \Drupal::moduleHandler()->invokeAll('mymodule_alter_something', [&$data]);

then the other developer can then make use of this by calling

function MYOTHERMODULE_mymodule_alter_something($data) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.