You are here

function list_extract_allowed_values in Drupal 7

Parses a string of 'allowed values' into an array.

Parameters

$string: The list of allowed values in string format described in list_allowed_values_string().

$field_type: The field type. Either 'list_number' or 'list_text'.

$generate_keys: Boolean value indicating whether to generate keys based on the position of the value if a key is not manually specified, and if the value cannot be used as a key. This should only be TRUE for fields of type 'list_number'.

Return value

The array of extracted key/value pairs, or NULL if the string is invalid.

See also

list_allowed_values_string()

1 call to list_extract_allowed_values()
list_allowed_values_setting_validate in modules/field/modules/list/list.module
Element validate callback; check that the entered values are valid.

File

modules/field/modules/list/list.module, line 280
Defines list field types that can be used with the Options module.

Code

function list_extract_allowed_values($string, $field_type, $generate_keys) {
  $values = array();
  $list = explode("\n", $string);
  $list = array_map('trim', $list);
  $list = array_filter($list, 'strlen');
  $generated_keys = $explicit_keys = FALSE;
  foreach ($list as $position => $text) {
    $value = $key = FALSE;

    // Check for an explicit key.
    $matches = array();
    if (preg_match('/(.*)\\|(.*)/', $text, $matches)) {
      $key = $matches[1];
      $value = $matches[2];
      $explicit_keys = TRUE;
    }
    elseif ($field_type == 'list_text' || $field_type == 'list_float' && is_numeric($text) || $field_type == 'list_integer' && is_numeric($text) && (double) $text == intval($text)) {
      $key = $value = $text;
      $explicit_keys = TRUE;
    }
    elseif ($generate_keys) {
      $key = (string) $position;
      $value = $text;
      $generated_keys = TRUE;
    }
    else {
      return;
    }

    // Float keys are represented as strings and need to be disambiguated
    // ('.5' is '0.5').
    if ($field_type == 'list_float' && is_numeric($key)) {
      $key = (string) (double) $key;
    }
    $values[$key] = $value;
  }

  // We generate keys only if the list contains no explicit key at all.
  if ($explicit_keys && $generated_keys) {
    return;
  }
  return $values;
}