Exposing data to Rules

Last updated on
11 December 2021

This documentation needs work. See "Help improve this page" in the sidebar.

Any Drupal module can integrate with Rules by providing new entity types using the Entity API to describe entity properties, or can integrate directly by using non-entity data structures. In Drupal 7, additional non-entity data types were registered using hook_rules_data_info(). In Drupal 8, that's now covered by the Typed Data API. Thus, you'd define a new data type using Typed Data (Entities are just one data type already provided by the Typed Data API). You can then use your new data type in Rules, just as you would any of the built-in data types provided by core Drupal. The following steps illustrate the steps needed to convert your Drupal 7 hook_rules_data_info() implementation into Typed Data plugins.

For structures like that, you'd need to define a complex data type, i.e. you can extend from the Map base class in the ComplexDataDefinition base class. The definition class needs to be used for defining the structure, for the actual instance class you can use whatever fits your use case. Could be that Map is already perfectly fine for your use case.

Tasks

  1. Make a list of data types that your module exposes to Rules. In Drupal 7, this is done using hook_rules_data_info() and hook_rules_data_info_alter(), which usually may be found in <modulename>/<modulename>.rules.inc (although, some modules implement this hook in <modulename>/<modulename>.module instead). Each type defined in hook_rules_data_info() appears as a top-level key in the array returned from this hook.
  2. Write a TypedData data definition class <modulename>/src/TypedData/<keyname>DataDefinition.php for each data type that hook_rules_data_info() generates.
  3. Write a TypedData DataType plugin <modulename>/src/Plugin/DataType/<keyname>.php for each data type that hook_rules_data_info() generates.
  4. Manually test, in the Rules UI, that your data type and all its properties shows up in the data selector when you edit a condition or action. To see your data, you will need to use an Event that puts your data in context.
  5. Manually review code to make sure all comments and text strings are correct for each data definition class and each DataType plugin.
  6. Manually test, by creating test reaction rules in the Rules UI, that your data type works as expected. It's useful to use the "Show a message on the site" action in these test rules and display your data in a token in the message.
  7. Write unit test cases for each event. Use the code in rules/tests/src/Unit/Integration/Event/* as examples.
  8. Write functional tests for each event. Use the code in rules/tests/src/Kernel/* as examples.

Try not to skip writing the tests - these are EXTREMELY useful for maintaining your module and for documenting how you expect your events to work.

Help improve this page

Page status: Needs work

You can: