Actions Plugin in Drupal 10

22 / Dec / 2023 by Radheshyam Kumawat 0 comments

Action Plugin Overview

The Actions module is a core module in Drupal that allows site builders and developers to create automated workflows by defining actions and triggers. In Drupal, actions refer to a set of tasks or operations that can be performed on a site. For example, an action can be sending an email, publishing content, or updating a database record.

Custom Actions Plugin

Here, A Drupal action is a functionality that performs a specific action when executed. For example, Archive Node or Make Content Sticky.

Actions use the annotation class Drupal\Core\Annotation\Action, and extend Drupal\Core\Action\ActionBase or Drupal\Core\Action\ConfigurableActionBase (if the action is configurable.)
Action Plugin definition is defined in Plugin Annotation. It has 3 required keys-

/**
* Provides an Archive Node Action.
*
* @Action(
*   id = "ttn_archive_node",
*   label = @Translation("Archive Node"),
*   type = "node",
*   category = @Translation("Custom")
* )
*/

id – ID of the Action Plugin
label – Name of the Action Plugin
type – Entity type to which the Action Plugin belongs to
category – (optional) Category of the Action Plugin

Archive Node Action

This is a simple action which requires no configuration. When it is run, it changes the alias of the node to /archive//. It also sets the title to have the word `Archive` in the front of it. Finally, it disables the sticky and promoted flags.

<?php

namespace Drupal\ttn\Plugin\Action;

use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\pathauto\PathautoState;

/**
 * Provides an Archive Node Action.
 *
 * @Action(
 *   id = "ttn_archive_node",
 *   label = @Translation("Archive Node"),
 *   type = "node",
 *   category = @Translation("Custom")
 * )
 */
class ArchiveNode extends ActionBase implements ContainerFactoryPluginInterface {

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Logger service.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $logger;

  /**
   * The path alias manager.
   *
   * @var \Drupal\path_alias\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * Language manager for retrieving the default Langcode.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = new static($configuration, $plugin_id, $plugin_definition);
    $instance->logger = $container->get('logger.factory')->get('ttn');
    $instance->messenger = $container->get('messenger');
    $instance->aliasManager = $container->get('path_alias.manager');
    $instance->languageManager = $container->get('language_manager');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function access($node, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $node */
    $access = $node->access('update', $account, TRUE)
      ->andIf($node->title->access('edit', $account, TRUE));
    return $return_as_object ? $access : $access->isAllowed();
  }

   /**
   * {@inheritdoc}
   */
  public function execute($node = NULL) {

    /** @var \Drupal\node\NodeInterface $node */

    $language = $this->languageManager->getCurrentLanguage()->getId();

    $old_alias = $this->aliasManager->getAliasByPath('/node/' . $node->id(), $language);

    $title = $node->getTitle();
    $date = $node->created->value;
    $year = date('Y', $date);
    $new_title = $this->t('[Archive] | @title', ['@title' => $title]);
    $node->setTitle($new_title);
    $node->setSticky(FALSE);
    $node->setPromoted(FALSE);

    $new_alias = '/archive/' . $year . $old_alias;
    $node->set("path", [
      'alias' => $new_alias,
      'langcode' => $language,
      'pathauto' => PathautoState::SKIP,
    ]);
    $node->save();
    $message = $this->t('Node with NID : @id Archived.', ['@id' => $node->id()]);
    $this->logger->notice($message);
    $this->messenger->addMessage($message);
  }

}

To get Action Plugin Discoverable, you need to add system.action.<plugin_id>.yml, which is placed in config/install.

The structure of the .yml file is shown below:

langcode: en
status: true
id: ttn_archive_node
label: 'Archive Node'
type: node
plugin: ttn_archive_node

Created Action Plugin can be viewed on the /admin/content page.

Custom Actions Existing Enable Module

Which is placed in config/install. Create .install file and use hook_update_N().

<?php 
// Install config. 
function ttn_update_9501(&$sandbox){ 
  $config_installer = \Drupal::service('config.installer'); 
  $config_installer->installDefaultConfig('module', 'ttn');
}

Run update.php

Conclusion

In the Actions module, you can create a customized workflow triggered by a specific event. The Actions module provides a user-friendly interface for defining and managing actions. For example, when a user submits a form on your website, you can trigger an action to send an email notification to the site administrator.

FOUND THIS USEFUL? SHARE IT

Tag -

Drupal

Leave a Reply

Your email address will not be published. Required fields are marked *