Dynamic Tabs in Drupal 8

Rohit Joshi
2 min readJun 19, 2018

--

Recently I was working on something where I had to create tabs. I was so excited that its just a tab and there should not be any problem.

I just created a YML file named mymodule.links.task.yml just like we do for tab creation. Content of YML file like -

my_module.user_label:
route_name: my_module.user_label

title: 'User label'
base_route: system.admin

Then I just cleared the cache and simply refresh the page and voila, I got an error.

From the error it was clear that the my route for which I was creating tab had a route parameter user and tab must require this value in order to render and thus I was getting error. Below is my route structure.

my_module.user_label:
path: '/admin/{user}/labels'
defaults:
_controller: '\Drupal\my_module\Controller\MyController::userLabel'
_title: 'User labels'
requirements:
_permission: 'administer system'

Then I just checked/searched in the drupal core and found out that tracker module is doing the same. So I just took this approach.

For this, we need to add a class key in the yml like this -

my_module.user_label:
route_name: my_module.user_label

title: 'User label'
base_route: system.admin
class: '\Drupal\my_module\Plugin\Menu\UserLabelDynamicTab'

and here is the class file -

<?php

namespace
Drupal\my_module\Plugin\Menu;

use Drupal\Core\Menu\LocalTaskDefault;
use Drupal\Core\Routing\RouteMatchInterface;

class UserLabelDynamicTab extends LocalTaskDefault {

/**
* {
@inheritdoc}
*/
public function getRouteParameters(RouteMatchInterface $route_match) {
$user_id = $route_match->getParameter('user');
return [
'user' => empty($user) ? \Drupal::currentUser()->id() : $user_id,
];
}

}

In class we simply checking if route has user parameter, then use it. If not, then use the current user’s id as parameter for the route.

And then I just cleared the cache and voila, it works. So now I know how to create dynamic tabs :)

--

--