How to create custom local actions programmatically in drupal 8 & 9
Local actions are defined in a YAML format, named after the module they are defined by. Such as menu_ui.links.action.yml
for this example from menu_ui module:
menu_ui.link_add:
route_name: menu_ui.link_add
title: 'Add link'
appears_on:
- menu_ui.menu_edit
menu_ui.menu_add:
route_name: menu_ui.menu_add
title: 'Add menu'
appears_on:
- menu_ui.overview_page
These actions appear like the following:
Example how to customize local action behaviour:
The default local action implementation is in LocalActionDefault. You can extend this class and modify the behaviour of a desired local action by providing the class on the local action. Such as to use a dynamic title for a local action:
<?php
namespace Drupal\example\Plugin\Menu\LocalAction;
use Drupal\Core\Menu\LocalActionDefault;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Defines a local action plugin with a dynamic title.
*/
class CustomLocalAction extends LocalActionDefault {
/**
* {@inheritdoc}
*/
public function getTitle() {
$title = new TranslatableMarkup("My @arg action", array(
'@arg' => 'dynamic-title',
));
return $title;
}
}
And refer this class in your example.links.action.yml
file:
example.content.action:
route_name: example.content.action
title: 'Example dynamic title action'
weight: -20
class: '\Drupal\example\Plugin\Menu\LocalAction\CustomLocalAction'
appears_on:
- example.content