n How to create custom local actions programmatically in drupal 8 & 9 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

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:

 

add menu

 

 

add Item action

 

 

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

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook