You are here

function rb_cck_action_force_to_allowed_values in Rules Bonus Pack 6

Action for 'rb_cck_action_force_to_allowed_values'.

File

./rb_cck.module, line 798
Functions for extending CCK field management with Rules.

Code

function rb_cck_action_force_to_allowed_values($node, $settings) {

  // Get required metadata for the field.
  $storage_key = rb_cck_field_storage_key($settings['field']);
  $allowed_values = array_keys(content_allowed_values(content_fields($settings['field'])));

  // If we don't have any allowed values defined, bail out by returning.
  if (!count($allowed_values)) {
    return;
  }

  // Get a quick reference for the field value, to increase readability. Note
  // that this variable is created by reference.
  $field_value =& $node->{$settings['field']}[0][$storage_key];

  // First check if the field is already ok. Note that the empty case is
  // included here, regardless of the fields required status – if a value is
  // missing, there isn't much we can do about it anyway.
  if (!$field_value || in_array($field_value, $allowed_values)) {
    return;
  }

  // Ok, so the field has a disallowed value. If we shouldn't do any smart
  // comparison, this means that we should just empty the field.
  if (!$settings['smart_compare']) {
    unset($node->{$settings['field']}[0]);
    return array(
      'node' => $node,
    );
  }

  // Then for the last part – doing 'smart comparison' using case-insensitive
  // comparison and trimming.
  foreach ($allowed_values as $allowed_value) {
    if (strtolower($allowed_value) == strtolower($field_value) || trim($allowed_value) == trim($field_value)) {
      $field_value = $allowed_value;
      return array(
        'node' => $node,
      );
    }
  }

  // Ok, if we got this far, then we have no plausible mapping for the field
  // value. Unset the value and return the node for saving.
  unset($node->{$settings['field']}[0]);
  return array(
    'node' => $node,
  );
}