options.module

Defines selection, check box and radio button widgets for text and numeric fields.

File

drupal/core/modules/options/options.module
View source
<?php

/**
 * @file
 * Defines selection, check box and radio button widgets for text and numeric fields.
 */
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\EntityInterface;
use Drupal\field\FieldUpdateForbiddenException;
use Drupal\options\Plugin\field\widget\OptionsWidgetBase;

/**
 * Implements hook_help().
 */
function options_help($path, $arg) {
  switch ($path) {
    case 'admin/help#options':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Options module defines various fields for storing a list of items, for use with the Field module. Usually these items are entered through a select list, checkboxes, or radio buttons. See the <a href="@field-help">Field module help page</a> for more information about fields.', array(
        '@field-help' => url('admin/help/field'),
      )) . '</p>';
      return $output;
  }
}

/**
 * Implements hook_field_info().
 */
function options_field_info() {
  return array(
    'list_integer' => array(
      'label' => t('List (integer)'),
      'description' => t("This field stores integer values from a list of allowed 'value => label' pairs, i.e. 'Lifetime in days': 1 => 1 day, 7 => 1 week, 31 => 1 month."),
      'settings' => array(
        'allowed_values' => array(),
        'allowed_values_function' => '',
      ),
      'default_widget' => 'options_select',
      'default_formatter' => 'list_default',
      'field item class' => '\\Drupal\\number\\Type\\IntegerItem',
    ),
    'list_float' => array(
      'label' => t('List (float)'),
      'description' => t("This field stores float values from a list of allowed 'value => label' pairs, i.e. 'Fraction': 0 => 0, .25 => 1/4, .75 => 3/4, 1 => 1."),
      'settings' => array(
        'allowed_values' => array(),
        'allowed_values_function' => '',
      ),
      'default_widget' => 'options_select',
      'default_formatter' => 'list_default',
      'field item class' => '\\Drupal\\number\\Type\\FloatItem',
    ),
    'list_text' => array(
      'label' => t('List (text)'),
      'description' => t("This field stores text values from a list of allowed 'value => label' pairs, i.e. 'US States': IL => Illinois, IA => Iowa, IN => Indiana."),
      'settings' => array(
        'allowed_values' => array(),
        'allowed_values_function' => '',
      ),
      'default_widget' => 'options_select',
      'default_formatter' => 'list_default',
      'field item class' => '\\Drupal\\text\\Type\\TextItem',
    ),
    'list_boolean' => array(
      'label' => t('Boolean'),
      'description' => t('This field stores simple on/off or yes/no options.'),
      'settings' => array(
        'allowed_values' => array(),
        'allowed_values_function' => '',
      ),
      'default_widget' => 'options_buttons',
      'default_formatter' => 'list_default',
      'field item class' => '\\Drupal\\number\\Type\\IntegerItem',
    ),
  );
}

/**
 * Implements hook_field_settings_form().
 */
function options_field_settings_form($field, $instance, $has_data) {
  $settings = $field['settings'];
  switch ($field['type']) {
    case 'list_integer':
    case 'list_float':
    case 'list_text':
      $form['allowed_values'] = array(
        '#type' => 'textarea',
        '#title' => t('Allowed values list'),
        '#default_value' => options_allowed_values_string($settings['allowed_values']),
        '#rows' => 10,
        '#element_validate' => array(
          'options_field_settings_form_validate_allowed_values',
        ),
        '#field_has_data' => $has_data,
        '#field' => $field,
        '#field_type' => $field['type'],
        '#access' => empty($settings['allowed_values_function']),
      );
      $description = '<p>' . t('The possible values this field can contain. Enter one value per line, in the format key|label.');
      if ($field['type'] == 'list_integer' || $field['type'] == 'list_float') {
        $description .= '<br/>' . t('The key is the stored value, and must be numeric. The label will be used in displayed values and edit forms.');
        $description .= '<br/>' . t('The label is optional: if a line contains a single number, it will be used as key and label.');
        $description .= '<br/>' . t('Lists of labels are also accepted (one label per line), only if the field does not hold any values yet. Numeric keys will be automatically generated from the positions in the list.');
      }
      else {
        $description .= '<br/>' . t('The key is the stored value. The label will be used in displayed values and edit forms.');
        $description .= '<br/>' . t('The label is optional: if a line contains a single string, it will be used as key and label.');
      }
      $description .= '</p>';
      $form['allowed_values']['#description'] = $description;
      break;
    case 'list_boolean':
      $values = $settings['allowed_values'];
      $off_value = array_shift($values);
      $on_value = array_shift($values);
      $form['allowed_values'] = array(
        '#type' => 'value',
        '#description' => '',
        '#value_callback' => 'options_field_settings_form_value_boolean_allowed_values',
        '#access' => empty($settings['allowed_values_function']),
      );
      $form['allowed_values']['on'] = array(
        '#type' => 'textfield',
        '#title' => t('On value'),
        '#default_value' => $on_value,
        '#required' => FALSE,
        '#description' => t('If left empty, "1" will be used.'),
        // Change #parents to make sure the element is not saved into field
        // settings.
        '#parents' => array(
          'on',
        ),
      );
      $form['allowed_values']['off'] = array(
        '#type' => 'textfield',
        '#title' => t('Off value'),
        '#default_value' => $off_value,
        '#required' => FALSE,
        '#description' => t('If left empty, "0" will be used.'),
        // Change #parents to make sure the element is not saved into field
        // settings.
        '#parents' => array(
          'off',
        ),
      );

      // Link the allowed value to the on / off elements to prepare for the rare
      // case of an alter changing #parents.
      $form['allowed_values']['#on_parents'] =& $form['allowed_values']['on']['#parents'];
      $form['allowed_values']['#off_parents'] =& $form['allowed_values']['off']['#parents'];
      break;
  }

  // Alter the description for allowed values depending on the widget type.
  if ($instance['widget']['type'] == 'options_onoff') {
    $form['allowed_values']['#description'] .= '<p>' . t("For a 'single on/off checkbox' widget, define the 'off' value first, then the 'on' value in the <strong>Allowed values</strong> section. Note that the checkbox will be labeled with the label of the 'on' value.") . '</p>';
  }
  elseif ($instance['widget']['type'] == 'options_buttons') {
    $form['allowed_values']['#description'] .= '<p>' . t("The 'checkboxes/radio buttons' widget will display checkboxes if the <em>Number of values</em> option is greater than 1 for this field, otherwise radios will be displayed.") . '</p>';
  }
  $form['allowed_values']['#description'] .= '<p>' . t('Allowed HTML tags in labels: @tags', array(
    '@tags' => _field_filter_xss_display_allowed_tags(),
  )) . '</p>';
  $form['allowed_values_function'] = array(
    '#type' => 'item',
    '#title' => t('Allowed values list'),
    '#markup' => t('The value of this field is being determined by the %function function and may not be changed.', array(
      '%function' => $settings['allowed_values_function'],
    )),
    '#access' => !empty($settings['allowed_values_function']),
    '#value' => $settings['allowed_values_function'],
  );
  return $form;
}

/**
 * Element validate callback; check that the entered values are valid.
 */
function options_field_settings_form_validate_allowed_values($element, &$form_state) {
  $field = $element['#field'];
  $has_data = $element['#field_has_data'];
  $field_type = $field['type'];
  $generate_keys = ($field_type == 'list_integer' || $field_type == 'list_float') && !$has_data;
  $values = options_extract_allowed_values($element['#value'], $field['type'], $generate_keys);
  if (!is_array($values)) {
    form_error($element, t('Allowed values list: invalid input.'));
  }
  else {

    // Check that keys are valid for the field type.
    foreach ($values as $key => $value) {
      if ($field_type == 'list_integer' && !preg_match('/^-?\\d+$/', $key)) {
        form_error($element, t('Allowed values list: keys must be integers.'));
        break;
      }
      if ($field_type == 'list_float' && !is_numeric($key)) {
        form_error($element, t('Allowed values list: each key must be a valid integer or decimal.'));
        break;
      }
      elseif ($field_type == 'list_text' && drupal_strlen($key) > 255) {
        form_error($element, t('Allowed values list: each key must be a string at most 255 characters long.'));
        break;
      }
    }

    // Prevent removing values currently in use.
    if ($has_data) {
      $lost_keys = array_diff(array_keys($field['settings']['allowed_values']), array_keys($values));
      if (_options_values_in_use($field, $lost_keys)) {
        form_error($element, t('Allowed values list: some values are being removed while currently in use.'));
      }
    }
    form_set_value($element, $values, $form_state);
  }
}

/**
* Form element #value_callback: assembles the allowed values for 'boolean' fields.
*/
function options_field_settings_form_value_boolean_allowed_values($element, $input, $form_state) {
  $on = NestedArray::getValue($form_state['input'], $element['#on_parents']);
  $off = NestedArray::getValue($form_state['input'], $element['#off_parents']);
  return array(
    $off,
    $on,
  );
}

/**
 * Implements hook_field_update_field().
 */
function options_field_update_field($field, $prior_field, $has_data) {
  drupal_static_reset('options_allowed_values');
}

/**
 * Returns the array of allowed values for a list field.
 *
 * The strings are not safe for output. Keys and values of the array should be
 * sanitized through field_filter_xss() before being displayed.
 *
 * @param $field
 *   The field definition.
 * @param $instance
 *   (optional) A field instance array. Defaults to NULL.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   (optional) The entity object. Defaults to NULL.
 *
 * @return
 *   The array of allowed values. Keys of the array are the raw stored values
 *   (number or text), values of the array are the display labels.
 */
function options_allowed_values($field, $instance = NULL, EntityInterface $entity = NULL) {
  $allowed_values =& drupal_static(__FUNCTION__, array());
  if (!isset($allowed_values[$field['uuid']])) {
    $function = $field['settings']['allowed_values_function'];

    // If $cacheable is FALSE, then the allowed values are not statically
    // cached. See options_test_dynamic_values_callback() for an example of
    // generating dynamic and uncached values.
    $cacheable = TRUE;
    if (!empty($function)) {
      $values = $function($field, $instance, $entity, $cacheable);
    }
    else {
      $values = $field['settings']['allowed_values'];
    }
    if ($cacheable) {
      $allowed_values[$field['uuid']] = $values;
    }
    else {
      return $values;
    }
  }
  return $allowed_values[$field['uuid']];
}

/**
 * Parses a string of 'allowed values' into an array.
 *
 * @param $string
 *   The list of allowed values in string format described in
 *   options_allowed_values_string().
 * @param $field_type
 *   The field type. Either 'list_number' or 'list_text'.
 * @param $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
 *   The array of extracted key/value pairs, or NULL if the string is invalid.
 *
 * @see options_allowed_values_string()
 */
function options_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)) {

      // Trim key and value to avoid unwanted spaces issues.
      $key = trim($matches[1]);
      $value = trim($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;
}

/**
 * Generates a string representation of an array of 'allowed values'.
 *
 * This string format is suitable for edition in a textarea.
 *
 * @param $values
 *   An array of values, where array keys are values and array values are
 *   labels.
 *
 * @return
 *   The string representation of the $values array:
 *    - Values are separated by a carriage return.
 *    - Each value is in the format "value|label" or "value".
 */
function options_allowed_values_string($values) {
  $lines = array();
  foreach ($values as $key => $value) {
    $lines[] = "{$key}|{$value}";
  }
  return implode("\n", $lines);
}

/**
 * Implements hook_field_update_forbid().
 */
function options_field_update_forbid($field, $prior_field, $has_data) {
  if ($field['module'] == 'options' && $has_data) {

    // Forbid any update that removes allowed values with actual data.
    $lost_keys = array_diff(array_keys($prior_field['settings']['allowed_values']), array_keys($field['settings']['allowed_values']));
    if (_options_values_in_use($field, $lost_keys)) {
      throw new FieldUpdateForbiddenException(t('A list field (@field_name) with existing data cannot have its keys changed.', array(
        '@field_name' => $field['field_name'],
      )));
    }
  }
}

/**
 * Checks if a list of values are being used in actual field values.
 */
function _options_values_in_use($field, $values) {
  if ($values) {
    $field = field_info_field_by_id($field['uuid']);
    $factory = Drupal::service('entity.query');
    foreach ($field['bundles'] as $entity_type => $bundle) {
      $result = $factory
        ->get($entity_type)
        ->condition($field['field_name'] . '.value', $values)
        ->count()
        ->accessCheck(FALSE)
        ->range(0, 1)
        ->execute();
      if ($result) {
        return TRUE;
      }
    }
  }
  return FALSE;
}

/**
 * Implements hook_field_validate().
 *
 * Possible error codes:
 * - 'list_illegal_value': The value is not part of the list of allowed values.
 */
function options_field_validate(EntityInterface $entity = NULL, $field, $instance, $langcode, $items, &$errors) {
  $allowed_values = options_allowed_values($field, $instance, $entity);
  foreach ($items as $delta => $item) {
    if (!empty($item['value'])) {
      if (!empty($allowed_values) && !isset($allowed_values[$item['value']])) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'list_illegal_value',
          'message' => t('%name: illegal value.', array(
            '%name' => $instance['label'],
          )),
        );
      }
    }
  }
}

/**
 * Implements hook_field_is_empty().
 */
function options_field_is_empty($item, $field) {
  if (empty($item['value']) && (string) $item['value'] !== '0') {
    return TRUE;
  }
  return FALSE;
}

/**
 * Implements hook_options_list().
 */
function options_options_list($field, $instance, $entity) {
  return options_allowed_values($field, $instance, $entity);
}

Functions

Namesort descending Description
options_allowed_values Returns the array of allowed values for a list field.
options_allowed_values_string Generates a string representation of an array of 'allowed values'.
options_extract_allowed_values Parses a string of 'allowed values' into an array.
options_field_info Implements hook_field_info().
options_field_is_empty Implements hook_field_is_empty().
options_field_settings_form Implements hook_field_settings_form().
options_field_settings_form_validate_allowed_values Element validate callback; check that the entered values are valid.
options_field_settings_form_value_boolean_allowed_values Form element #value_callback: assembles the allowed values for 'boolean' fields.
options_field_update_field Implements hook_field_update_field().
options_field_update_forbid Implements hook_field_update_forbid().
options_field_validate Implements hook_field_validate().
options_help Implements hook_help().
options_options_list Implements hook_options_list().
_options_values_in_use Checks if a list of values are being used in actual field values.