Actions
In Drupal 7, actions are defined in hook_rules_action_info(). If you are already familiar with Rules actions in Drupal 7, then Porting Actions will show you how D7 Rules actions correspond to D8 Rules actions. The remainder of this page does not assume prior knowledge of Rules in Drupal 7.
In Drupal 8, Actions are no longer defined through a hook. They are plugins defined in PHP class extending RulesActionBase, and are stored in <module_name>/src/Plugin/RulesAction/. The annotation is @RulesAction.
As we saw with Condition plugins, the only required thing here is the plugin annotation to declare the context variables and a protected function doExecute() which accepts these context variables are arguments and performs the required action. Again, this implementation can get more complicated if your action 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 action, which in D7 you might have put into module_name.rules.inc, should be protected class methods declared in the Action plugin class.
To implement a Rules Action Plugin, place your plugin code in <module_name>/src/Plugin/RulesAction, for example:
/**
* Provides a 'Delete entity' action.
*
* @RulesAction(
* id = "rules_entity_delete",
* label = @Translation("Delete entity"),
* category = @Translation("Entity"),
* context_definitions = {
* "entity" = @ContextDefinition("entity",
* label = @Translation("Entity"),
* description = @Translation("Specifies the entity, which should be deleted permanently.")
* )
* }
* )
*/
class EntityDelete extends RulesActionBase {
/**
* Deletes the Entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to be deleted.
*/
protected function doExecute(EntityInterface $entity) {
$entity->delete();
}
}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