Skip to main content
Category:

Rules is a tool that enables you to define automatic, conditionally executed actions, triggered by various types of events. in this tutorial I’ll show you how to create custom rules action in Drupal 8.

Create a module

In Drupal 8, it is necessary to create an info.yml file that contains the metadata for every custom module. you will need to create the codimth_custom_rules_action.info.yml file under the modules/custom/codimth_custom_rules_action folder. Inside this file enter following:

name: Codimth Custom Rules Action
description: Create a custom rules Action
package: CodimTh
type: module
core: 8.x
dependencies:
  - rules

Once the folder and file has been created, you can go to your Drupal dashboard and enable the custom module we have just created.

Create a RulesAction Class

Now, we’ll create a class that will contain the logic of our action. we’ll place our ShowMessage.php class under the modules/custom/codimth_custom_rules_action/src/Plugin/RulesAction directory. 
The class file should contain annotation as well. The annotation allows us to identify the action, also this class will contain doExecute() method.

doExecute() method will contain the logic of our action.

Now, this is what the class file should contain in the end:

<?php

namespace Drupal\codimth_custom_rules_action\Plugin\RulesAction;

use Drupal\rules\Core\RulesActionBase;

/**
 * Provides a 'Show message on your site' action.
 *
 * @RulesAction(
 *   id = "codimth_custom_rules_action_show_message",
 *   label = @Translation("Codimth Show message"),
 *   category = @Translation("CodimTh"),
 *   context = {
 *     "message" = @ContextDefinition("string",
 *       label = @Translation("Message"),
 *       description = @Translation("write your message"),
 *     ),
 *     "type" = @ContextDefinition("string",
 *       label = @Translation("Message type"),
 *       description = @Translation("Message type: status, warning or error "),
 *     ),
 *   }
 * )
 *
 */
class ShowMessage extends RulesActionBase
{

    /**
     * @param $name
     */
    protected function doExecute($message, $type)
    {
        \Drupal::messenger()->addMessage(t($message), $type);
    }

}

Now, go back to your site, and you should be able to see the Action you have just created. follow these screenshots to know how to use it.

show message action

 

how to use show message action

 

Next steps

  • Clear your Drupal 8 caches. To do this I use this Drush command: drush cr if you don’t currently use Drush, I highly recommend using it, or the Drupal Console.
  • I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.

 

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.