Providing new variables

Last updated on
30 November 2019

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

Actions may provide new variables to Rules, which in turn other actions may pick up. For that describe the variables that the action provides in hook_rules_action_info() and return the values of the provided variables.

As example consider the implementation of the add a variable action:

/**
 * Implements hook_rules_action_info() on behalf of the pseudo data module.
 * @see rules_core_modules()
 */
function rules_data_action_info() {
  $return['variable_add'] = array(
    'label' => t('Add a variable'),
    'named parameter' => TRUE,
    'parameter' => array(
      'type' => array(
        'type' => 'text',
        'label' => t('Type'),
        'options list' => 'rules_data_action_variable_add_options',
        'description' => t('Specifies the type of the variable that should be added.'),
        'restriction' => 'input',
      ),
      'value' => array(
        'type' => 'unknown',
        'label' => t('Value'),
      ),
    ),
    'provides' => array(
      'variable_added' => array(
        'type' => 'unknown',
        'label' => t('Added variable'),
      ),
    ),
    'group' => t('Data'),
    'base' => 'rules_action_variable_add',
    'callbacks' => array(
      'form_alter' => 'rules_action_type_form_alter',
      'validate' => 'rules_action_create_type_validate',
    ),
  );
  return $return;
}

/**
 * Action: Add variable.
 */
function rules_action_variable_add($args, $element) {
  return array('variable_added' => $args['value']);
}

As seen the value for the newly provided variable is returned by action.

Additionally this examples shows the 'info alter' callback can be used to alter the action info depending on some parameter settings. Thus in the example the callback ensures the action-info of a configured action correctly states the configured data type of the provided variable.


/**
 * Info alteration callback for variable add action.
 */
function rules_action_variable_add_info_alter(&$element_info, RulesAbstractPlugin $element) {
  if (isset($element->settings['type']) && $type = $element->settings['type']) {
    $cache = rules_get_cache();
    $type_info = $cache['data_info'][$type];
    $element_info['parameter']['value']['type'] = $type;
    $element_info['parameter']['value']['label'] = $type_info['label'];
    $element_info['provides']['variable_added']['type'] = $type;
  }
}

Help improve this page

Page status: No known problems

You can: