n How to create custom rules condition in Drupal 8 | 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:

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 condition 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_condition.info.yml file under the modules/custom/codimth_custom_rules_condition folder. Inside this file enter following:

name: Codimth Custom Rules Condition
description: Create a custom rules condition
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 Condition Class

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

doEvaluate() method will contain the logic of our condition.

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

<?php

namespace Drupal\codimth_custom_rules_condition\Plugin\Condition;

use Drupal\node\NodeInterface;
use Drupal\rules\Core\RulesConditionBase;

/**
 * Provides a 'Node ID is' condition.
 *
 * @Condition(
 *   id = "codimth_custom_rules_condition_node_id_is",
 *   label = @Translation("Node ID is"),
 *   category = @Translation("Node"),
 *   context = {
 *     "node" = @ContextDefinition("entity:node",
 *       label = @Translation("Node")
 *     ),
 *     "ids" = @ContextDefinition("string",
 *       label = @Translation("IDs of Nodes"),
 *       description = @Translation("IDs of Nodes"),
 *       multiple = TRUE
 *     )
 *   }
 * )
 *
 */
class NodeIDIs extends RulesConditionBase
{

    /**
     * @param \Drupal\node\NodeInterface $node
     *   The node to check.
     *
     * @return bool
     *   TRUE if the node id existe in $ids array.
     */
    protected function doEvaluate(NodeInterface $node, $ids)
    {
        return in_array($node->id(),$ids);
    }


}

 

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

Node ID is

 

How to use Node Id is condition

 

Next steps


 

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.