I have written a RulesAction. That works great.
Now I want to execute this Rule from Code.

In Detail I want to call a menu route and execute my custom RulesAction.
The menu route is defined in the same custom module and extends from ControllerBase.

But how to invoke the RuleAction?
In Drupal 7 there was the rules_invoke_component() Methode.

Comments

sreher created an issue. See original summary.

zhiqiang.qiu’s picture

same question? anyone can help? I'm not sure, it should be like this?

$event = new UserLoginEvent($account);
  $event_dispatcher = \Drupal::service('event_dispatcher');
  $event_dispatcher->dispatch(UserLoginEvent::EVENT_NAME, $event);
wombatbuddy’s picture

TR’s picture

Status: Active » Fixed

#2 was answered by #3.

For the original post, the best answer to "how do I do X programmatically" is always going to be "look at the test cases". Everything in Rules has tests, and these contain working examples of how to use every feature.

Here's a modified version of DataConvertTest to show you how this works. You may save this script and execute it with drush php:script

<?php

    /** @var \Drupal\rules\Core\RulesActionManager $actionManager */
    $actionManager = \Drupal::service('plugin.manager.rules_action');

    /** @var \Drupal\rules\Core\RulesActionInterface $action */
    $action = $actionManager->createInstance('rules_data_convert');

    // Test the conversion to integer.
    $action->setContextValue('value', 1.5);
    $action->setContextValue('target_type', 'integer');

    if (!empty($rounding_behavior)) {
      $action->setContextValue('rounding_behavior', $rounding_behavior);
    }

    // For data_convert, once the action has been configured above we can
    // accurately set a datatype for the provided variable. It still works
    // if we don't refine our provided context, but we can't check against
    // the specific 'integer' data type, only against the generic 'any' type.
    $action->refineContextDefinitions([]);
    $action->execute();

    $result = $action->getProvidedContext('conversion_result')->getContextData();

    print_r($result->getValue() . "\n");
    print_r($result->getDataDefinition()->getDataType() . "\n");

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.