How to make a Drupal 8 local task title dynamic Sven DecabooterThu, 05/09/2019 - 17:00?>
When defining local tasks (= tabs) in your Drupal 8 modules, you can specify a title for the tab via the 'title' property in your [MODULENAME].links.task.yml file.
However, in some cases you might want to make the task title dynamic, e.g. depending on the context of the entity where the tab is displayed.
This can be achieved by overriding the \Drupal\Core\Menu\LocalTaskDefault class with your own class for that tab.
Here is an example that uses a callback function to dynamically set the title, both for the route and the local task:
Add the dynamic logic to your controller
File: my_module/src/Controller/DynamicTabController.phpt('Dynamic tab for @type', ['@type' => $node->bundle()]); } }
Use the dynamic title callback for your route
File: my_module/my_module.routing.ymlentity.node.dynamic_tab: path: '/node/{node}/dynamic_tab' defaults: _entity_form: 'node.dynamic_tab' _title_callback: '\Drupal\my_module\Controller\DynamicTabController::getDynamicTabTitle' requirements: _entity_access: 'node.view'
Add your custom LocalTask plugin
File: my_module/src/Plugin/Menu/LocalTask/DynamicTabLocalTask.phpattributes->get('node'); if ($node instanceof NodeInterface) { $controller = new DynamicTabController(); return $controller->getDynamicTabTitle($node); } return $this->t('Default'); } }
Set your custom class for your local task
File: my_module/my_module.links.task.ymlentity.node.dynamic_tab: route_name: entity.node.dynamic_tab base_route: entity.company.canonical title: 'Default' class: '\Drupal\my_module\Plugin\Menu\LocalTask\DynamicTabLocalTask'
Now the dynamic title will be used to render your tab name, and the tab page title.