Drupal 7 Rules Guide

A short list of tricks to work with different parts of Rules. I'll continue adding to this guide as I learn.

RulesAnd Object

Ubercart tax rules are configured to use the RulesAnd (rules_and function) which changes how you retrieve getElementName() and settings(). Their file uc_taxes.rules_defaults.inc is responsible for creating a settings page where you can add conditions to a new tax rate.  Here's the code:

/**
 * Implements hook_default_rules_configuration().
 *
 * Creates a condition set for each tax rule.
 */
function uc_taxes_default_rules_configuration() {
  $configs = array();

  // Loop through all the defined tax rates.
  foreach (uc_taxes_rate_load() as $rate) {
    $set = rules_and(array(
      'order' => array('type' => 'uc_order', 'label' => 'Order'),
    ));
    $set->label = t('@name conditions', array('@name' => $rate->name));

    $configs['uc_taxes_' . $rate->id] = $set;
  }
  return $configs;
}

Note line 11 where it reads $set = rules_and(array(

We ran into a situation where we needed to do a copy and paste from an existing rule to a new rule because of the addition of external tax rates (QuickBooks synchronization of taxes to Drupal).  This wasn't easy to figure out at first because of how Rules works.  Here's the code:

// Copy rules_config from previous rule into new one.
$rule_config = rules_config_load('existing_rule_name_here');
if ($rule_config) {
  $rule_config->name = 'new name';
  // Adds a new RulesAnd.
  $rule_config->id = 0;
  $rule_config->save();
}
Retriving conditions within a RulesAnd Object

What if you want to pull the condition(s) that exist within a RulesAnd object?  It's super easy but only after you search through code and test (doesn't seem to be well documented).  Here's the code:

// Copy rules_config from previous rule into new one.
$prev_rule = rules_config_load('previous_rule_name');
$new_rule = rules_config_load('new_rule_name');
if ($prev_rule && $new_rule) {
  foreach ($prev_rule->elements() as $element) {
    $rule_config_new->condition($element->getElementName(), $element->settings);
    $rule_config_new->save();
  }
}

 

Leave a comment