This recipe explains how to provide default rule configurations in code. The advantage of that is that we can keep our configurations in code and use version control, such as, SVN or Git.
In our custom module's folder, we add a new file called
custom.rules_defaults.inc
and declare the rule configuration by implementinghook_default_rules_configuration()
. The contents of the file are as follows:/** * Implements hook_default_rules_configuration() */ function custom_default_rules_configuration() { $rule = rules_reaction_rule(); $rule->label = 'Default Rule'; $rule->active = TRUE; $rule->event('node_insert') ->condition('data_is', array('data:select' => 'node:type', 'value' => 'article')) ->condition(rules_condition('data_is', array('data:select' => 'node:author:uid', 'value' => 1))->negate()) ->action('drupal_message', array('message' => 'Hey [node:author], thanks for creating a new article!')); $configs['custom_default_rule'] = $rule; return $configs; }
After clearing the caches, our newly created default rule will become available in the list of configurations, as shown in the following screenshot:
Using hook_default_rules_configuration()
, we can define our rule configuration in code using Rules' methods for Events, Conditions, and Actions. Rules will look for a file *.rules_defatuls.inc
in our module's folder, and automatically add our default rule to the available configurations after clearing the caches.
Rules is compatible with the Features
module, which provides a centralized API for exporting and importing configuration from the database. This is also an effective way to manage configuration in code and version control systems.
It is also possible to modify a default rule configuration in code. For that we could use hook_default_rules_configuration_alter()
in our *.rules_defaults.inc
file.
/** * Implements hook_default_rules_configuration_alter() */ function custom_default_rules_configuration_alter(&$configs) { $configs['custom_default_rule']->condition('data_is', array('data:select' => 'node:is_new', 'value' => TRUE)); }
Rules tracks the state of a Rule configuration that has been added programmatically. What that means is that it can determine whether an imported configuration is in its default state (not modified compared to the code) or overridden (modified using the UI, but not in code). When a configuration is modified, Rules allows to revert it back to its original state.

By clicking on that, we're telling Rules that it should re-read the configuration that we've defined in code and revert it to its original state.