Do you want to know how to Drupal?

Let's Drupal

How to add a local task (tab) in Drupal?

In Drupal we can display secondary menu as tabs. If you don't know what it is open any content item (node) as administrator and on the top you can see:

  • View 
  • Edit
  • Delete

and so on

In this post we will review how to add a static local task

In order to have a new tab you need to create a new YML file in the root of your module. This file has a specific name your_module_name.links.task.yml. You have to replace your_module_name with the name of your module

Then you can define the local task you want to provide in the next format  

your_module.admin: # Unique id of your tasks normally prefixed with route name or entity name 
  route_name: your_module.custom_settings # Route which will be opened, when we click on the tab
  title: 'Settings' #Title of your tab
  base_route: entity.node.canonical #Parent route (the default tab) 
  parent_id: entity.node.canonical # Optional: We define the parent tab id here
  weight: 100 # Defines the order for the tab

Let's review a simple example. I have module local_tasks. You can find it here  https://github.com/LOBsTerr/drupal-modules-examples/tree/master/local_tasks or create your own.

I have a custom page, which will provide the extra settings for nodes, in fact it will just display the title of a node for a sake of simplicity. This a route for which we are going to add a tab. You need to add it to local_tasks.routing.yml

 

local_tasks.node_extra_settings:
  path: '/node/{node}/extra-settings'
  defaults:
    _controller: '\Drupal\local_tasks\Controller\LocalTasksController::nodeExtraSettings'
    _title: 'Node extra settings'
  requirements:
    _permission: 'access content'
  options:
    parameters:
      node:
        type: 'entity:node'

 

The definition of the tab you need to add to local_tasks.links.task.yml

# In this example we add an additional tab to the node page
local_tasks.node_extra_settings: # The ID of local task is the same as route, to make it easier to control.
  route_name: 'local_tasks.node_extra_settings' # The name of our route, provided in local_tasks.routing.yml.
  title: 'Extra settings' # This string will be displayed as a title of a tab.
  base_route: 'entity.node.canonical' # We use node entity in order to group tabs together.
  weight: 100

Now, you need install the module local_tasks or to clean the cache if you do it your own module.

Open any node (node/[NID]), you should see a new tab "Extra settings". Also, you can open directly the page node/[NID]/extra-settings

In the next posts, we will review how to add sublevels of tabs, to define the default local task and how to add local tasks dynamically