Jan 06, 2020 in Drupal 8, Snippets

Goodbye preprocess functions! Welcome to drupal 8. We use a nice plug-in to get control over our menu item and to show html inside the title. In this case we show a counter of the amount of messages a user has.

Create a file called MyMessagesMenuLink.php in src/Plugin/Menu:

namespace Drupal\MYMODULE\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;

/**
 * A menu link that displays number of points.
 */
class MyMessagesMenuLink extends MenuLinkDefault {

  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    $count = 0;
    if(\Drupal::currentUser()->isAuthenticated()) {
      $messages = \Drupal::entityTypeManager()
        ->getStorage('message')
        ->loadByProperties(['user_id' => \Drupal::currentUser()->id()]);
      $count = count($messages);
    }
    return $this->t('My messages <span class="badge badge-dark">@count</span>', ['@count' => $count]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return 0;
  }

}

Next, we'll need to inform drupal to automatically add a menu item to its system. Inside mymodule.links.menu.yml add:

my_module.my_messages:
  route_name: my_module.my_messages_page_controller 
  menu_name: main
  class: Drupal\mymodule\Plugin\Menu\MyMessagesMenuLink
  weight: 30

Clear caches and you should see a menu link with html inside it. You could tweak it in many ways, for example show a different text for anonymous users, play with caching and so on. Do not forget to create your my_module.my_messages_page_controller