How to override a local task in Drupal 8

By Ronald van Belzen | June 16, 2018

In the previous blog post I added a local task next to the "Published comments" and "Unapproved comments" under the Content "Comments" menu.

The new local task was for the display of a list of comments that were designated as spam comments, and a count of the number of these comments was uncluded. However, this count has in common with the count of unapproved comments that spam comment are unpublished. So the count of unpublished comments will include the number of spam comments.

To correct this we will need to override the local task menu for unapproved comments.

The mechanism for altering the local tasks of another module is by using hook_menu_local_tasks_alter(). The example shown in the documentation adds a top-level menu to all pages, but here we are going to override an existing sub-level menu on only 3 pages.

/* mycomment.module */

 * Set the unapproved comments count.
 * Implements hook_menu_local_tasks_alter().
function mycomment_menu_local_tasks_alter(&$data, $route_name, &$cacheability) {
  if ($route_name == 'comment.admin' ||
    $route_name == 'comment.admin_approval' ||
    $route_name == 'mycomment.admin_comment_spam'
   ) {
    $data['tabs'][1]['comment.admin_approval']['#link']['title'] =
      t('Unapproved comments (@count)', [
        '@count' => get_actual_unapproved_comments(),

The routes are those of the "Published comments", "Unapproved comments" and "Spam comments". Each level of menus in the $data array is enclosed in each own array item. Index 0 is for the top level menus, while the "Unapproved comments" local task can be found in the $data item with index 1.

The title of the link of the "Unapproved comment" is overridden. The new count of unapproved comments without spam comments is delivered by the function get_actual_unapproved_comments().

/* mycomment.module */

 * Get the number of unapproved comments.
 * @return int
 *   The number of unapproved comments excluding the spam comments.
function get_actual_unapproved_comments() {
  $query = \Drupal::entityQuery('comment');
  $query->condition('status', 0);
  $orCondition = $query->orConditionGroup();
  $orCondition->condition('field_spam', NULL, 'IS NULL');
  $orCondition->condition('field_spam', FALSE, '=');
  $ids = $query->execute();
  return count($ids);


Add new comment