2
votes

I'm very new in Drupal 8 and I have issue now with hook. Mainly I though that I don't clearly understand structure and hook definition in Drupal 8.

So my main problem is that I have some hook to interact with main menu (add custom class name to ul, li and link, a tag). I can do it by changing template file and now try to do it with any hook.

Although I found that some hook relating to menu ex. hook_contextual_links_alter (link: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/function/hook_contextual_links_alter/8.9.x).

At the end of this hook we have the code related:

function hook_contextual_links_alter(array &$links, $group, array $route_parameters) {   
  if ($group == 'menu') {
    // Dynamically use the menu name for the title of the menu_edit contextual
    // link.
    $menu = \Drupal::entityTypeManager()
      ->getStorage('menu')
      ->load($route_parameters['menu']);
    $links['menu_edit']['title'] = t('Edit menu: @label', [
      '@label' => $menu
        ->label(),
    ]);   
  } 
}

So I have installed devel module with kint function and in my .theme file and try:

function hook_contextual_links_alter(array &$links, $group, array $route_parameters) {   
  kint($links);
}

and then reload my Home page but nothing showed. But I can get some information about other like:

function eg_learn_theme_suggestions_page_alter(&$suggestions, $variables) {   
  kint($suggestions); 
}

So what happens here? Can you help to explain if how I can print the variable of this hook (in .theme file) and the site page to see the printing variable?

In general when I found a hook, how I can print there array and check it in website?

1
Thanks for your help. Your 2nd idea is right.There are some hook for module and hook for changing front-end. I have change this hook where it could be interacted with modules not the front-end that's why I don't see any change. Anyway, many thanks for your view and support. - Duc Pham

1 Answers

3
votes

There are some problems about your approach:

  1. When implementing a hook, you must replace "hook" with the module name/theme name where you put the hook function inside. For example, if you want implement hook_contextual_links_alter in your_custom module, it becomes your_custom_contextual_links_alter().
  2. Not all hook can be implemented in the theme. Some hook can only be implemented in modules (in .module file). You can read more here.
  3. In your case, I think hook_preprocess_menu would be more suitable. You can implement it in your custom theme like this:
    function <your_theme_name>_preprocess_menu(&$variables) {
      if ($variables['menu_name'] == 'main') {
        kint($variables);
      }
    }