Conditions
In Drupal 7, conditions are defined in hook_rules_condition_info(). If you are already familiar with Rules conditions in Drupal 7, then Porting Conditions will show you how D7 Rules conditions correspond to D8 Rules conditions. The remainder of this page does not assume prior knowledge of Rules in Drupal 7.
In Drupal 8, Conditions are no longer defined through a hook. They are plugins defined in PHP class extending RulesConditionBase, and are stored in <module_name>/src/Plugin/Condition/.
The annotation is @Condition. Note that this annotation is the same as core Conditions, but Rules conditions extend the core capabilities and add "context improvements". Rules actually replaces the core plugin.manager.condition service with its own service - see RulesServiceProvider.
To implement a Rules Condition plugin, place your plugin code in <module_name>/src/Plugin/Condition/. For example:
/**
* Provides a 'Node is sticky' condition.
*
* @Condition(
* id = "rules_node_is_sticky",
* label = @Translation("Node is sticky"),
* category = @Translation("Node"),
* context_definitions = {
* "node" = @ContextDefinition("entity:node",
* label = @Translation("Node")
* )
* }
* )
*/
class NodeIsSticky extends RulesConditionBase {
/**
* Check if the given node is sticky.
*
* @param \Drupal\node\NodeInterface $node
* The node to check.
*
* @return bool
* TRUE if the node is sticky.
*/
protected function doEvaluate(NodeInterface $node) {
return $node->isSticky();
}
}The only required thing here is the plugin annotation to declare the context variables and a protected function doEvaluate() which accepts these context variables as arguments and returns a boolean indicating whether the condition was satisfied. This implementation can get more complicated if the evaluation of your condition requires services - then these should be injected into the plugin rather than making static \Drupal::service() calls. See Services and dependency injection in Drupal 8 for details.
Any helper functions needed for your condition, which in Drupal 7 you might have put into <module_name>.rules.inc, should be protected class methods declared in the Condition plugin class.
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion