[Drupal] How to export and convert default Drupal rule to a programmatic rule?

By | 24th Jun 2015 | 3 min read

For a Drupal site I had a requirement to create a Rule using the rules modules. It seemed to be working fine. Then I needed to convert the rule to a programmatic rule that I can include inside my custom module.

For doing this I followed the below steps:

Step 1: Creating your rule

The easiest way to initially set up the rule is to use the Rules UI interface. Coding directly would do but you are more likely to make mistakes than if you are just copying some exported text from the Rules interface.

Step 2: Exporting your rule

Within the rules UI you can find all the rules including the rule you have created.

Step 3: Adding the export code to your module

In your MODULE_NAME.rules_defaults.inc file, you should have the following set up as the very basic code.

<?php
function MODULE_NAME_default_rules_configuration() {
  $configs = array();
  return $configs;
}
?>

Note that you will need to change MODULE_NAME to your actual module name and the closing ?> tag should not be at the end of your file, that is something that the syntax highlighter adds on automatically.

To have the rule process from the exported code we need to run it through the function rules_import(). This will change the export code in to a usable format for the Rules module. This then needs to be added to the $configs array.

<?php
function MODULE_NAME_default_rules_configuration() {
  $configs = array();
  $rule = '{ "commerce_checkout_order_email" : {
    "LABEL" : "Send an order notification e-mail",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "4",
    "REQUIRES" : [ "rules", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "DO" : [
      { "mail" : {
          "to" : [ "commerce-order:mail" ],
          "subject" : "Order [commerce-order:order-number] at [site:name]",
          "message" : "Thanks for your order [commerce-order:order-number] at [site:name].\n\nIf this is your first order with us, you will receive a separate e-mail with login instructions. You can view your order history with us at any time by logging into our website at:\n\n[site:login-url]\n\nYou can find the status of your current order at:\n\n[commerce-order:customer-url]\n\nPlease contact us if you have any questions about your order.",
          "from" : ""
        }
      }
    ]
  }
}';
  $configs['commerce_checkout_order_email'] = rules_import($rule);
  return $configs;
}
?>

You can define multiple rules through this function and you also have the luxury of being able to programmatically define rules based on other aspects of the site (such as rule per user role or content type. Here is an example say, setting up different pricing groups per user role in Drupal Commerce).

If you are adding your rule in a development site, you will need to run cron before the rule appears within Rules UI. The same need to be followed for any changes you make to the rule in code.