options.module 6.5 KB
Newer Older
1 2 3 4 5 6
<?php

/**
 * @file
 * Defines selection, check box and radio button widgets for text and numeric fields.
 */
7

8
use Drupal\Core\Url;
9
use Drupal\Core\Entity\FieldableEntityInterface;
10
use Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException;
11
use Drupal\Core\Field\FieldStorageDefinitionInterface;
12
use Drupal\Core\Routing\RouteMatchInterface;
13
use Drupal\field\FieldStorageConfigInterface;
14

15 16 17
/**
 * Implements hook_help().
 */
18
function options_help($route_name, RouteMatchInterface $route_match) {
19 20
  switch ($route_name) {
    case 'help.page.options':
21 22
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
23
      $output .= '<p>' . t('The Options module allows you to create fields where data values are selected from a fixed list of options. Usually these items are entered through a select list, checkboxes, or radio buttons. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for general information on fields and how to create and manage them. For more information, see the <a href=":options_do">online documentation for the Options module</a>.', [':field' => Url::fromRoute('help.page', ['name' => 'field'])->toString(), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? Url::fromRoute('help.page', ['name' => 'field_ui'])->toString() : '#', ':options_do' => 'https://www.drupal.org/documentation/modules/options']) . '</p>';
24 25 26
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Managing and displaying list fields') . '</dt>';
27
      $output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the list fields can be configured separately. See the <a href=":field_ui">Field UI help</a> for more information on how to manage fields and their display.', [':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? Url::fromRoute('help.page', ['name' => 'field_ui'])->toString() : '#']) . '</dd>';
28 29 30 31 32
      $output .= '<dt>' . t('Defining option keys and labels') . '</dt>';
      $output .= '<dd>' . t('When you define the list options you can define a key and a label for each option in the list. The label will be shown to the users while the key gets stored in the database.') . '</dd>';
      $output .= '<dt>' . t('Choosing list field type') . '</dt>';
      $output .= '<dd>' . t('There are three types of list fields, which store different types of data: <em>float</em>, <em>integer</em> or, <em>text</em>. The <em>float</em> type allows storing approximate decimal values. The <em>integer</em> type allows storing whole numbers, such as years (for example, 2012) or values (for example, 1, 2, 5, 305). The <em>text</em> list field type allows storing text values. No matter which type of list field you choose, you can define whatever labels you wish for data entry.') . '</dd>';
      $output .= '</dl>';
33 34 35 36
      return $output;
  }
}

37
/**
38
 * Implements hook_ENTITY_TYPE_update() for 'field_storage_config'.
39
 */
40
function options_field_storage_config_update(FieldStorageConfigInterface $field_storage) {
41 42 43
  drupal_static_reset('options_allowed_values');
}

44
/**
45
 * Implements hook_ENTITY_TYPE_delete() for 'field_storage_config'.
46
 */
47
function options_field_storage_config_delete(FieldStorageConfigInterface $field_storage) {
48 49 50
  drupal_static_reset('options_allowed_values');
}

51 52 53 54
/**
 * 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
55 56
 * sanitized through \Drupal\Core\Field\FieldFilteredMarkup before being
 * displayed.
57
 *
58 59
 * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $definition
 *   The field storage definition.
alexpott's avatar
alexpott committed
60
 * @param \Drupal\Core\Entity\FieldableEntityInterface|null $entity
61 62
 *   (optional) The specific entity when this function is called from the
 *   context of a specific field on a specific entity. This allows custom
63
 *   'allowed_values_function' callbacks to either restrict the values or
64 65
 *   customize the labels for particular bundles and entities. NULL when
 *   there is not a specific entity available, such as for Views filters.
66
 *
67
 * @return array
68 69
 *   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.
70 71
 *
 * @see callback_allowed_values_function()
72
 */
73
function options_allowed_values(FieldStorageDefinitionInterface $definition, FieldableEntityInterface $entity = NULL) {
74
  $allowed_values = &drupal_static(__FUNCTION__, []);
75

76
  $cache_keys = [$definition->getTargetEntityTypeId(), $definition->getName()];
77 78 79 80 81
  if ($entity) {
    $cache_keys[] = 'entity';
  }
  $cache_id = implode(':', $cache_keys);

82
  if (!isset($allowed_values[$cache_id])) {
83
    $function = $definition->getSetting('allowed_values_function');
84 85 86 87 88
    // 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)) {
89
      $values = $function($definition, $entity, $cacheable);
90 91
    }
    else {
92
      $values = $definition->getSetting('allowed_values');
93 94 95
    }

    if ($cacheable) {
96
      $allowed_values[$cache_id] = $values;
97 98 99 100 101 102
    }
    else {
      return $values;
    }
  }

103
  return $allowed_values[$cache_id];
104 105 106
}

/**
107
 * Implements hook_field_storage_config_update_forbid().
108
 */
109
function options_field_storage_config_update_forbid(FieldStorageConfigInterface $field_storage, FieldStorageConfigInterface $prior_field_storage) {
110
  if ($field_storage->getTypeProvider() == 'options' && $field_storage->hasData()) {
111
    // Forbid any update that removes allowed values with actual data.
112 113
    $allowed_values = $field_storage->getSetting('allowed_values');
    $prior_allowed_values = $prior_field_storage->getSetting('allowed_values');
114
    $lost_keys = array_keys(array_diff_key($prior_allowed_values, $allowed_values));
115
    if (_options_values_in_use($field_storage->getTargetEntityTypeId(), $field_storage->getName(), $lost_keys)) {
116
      throw new FieldStorageDefinitionUpdateForbiddenException("A list field '{$field_storage->getName()}' with existing data cannot have its keys changed.");
117 118 119 120 121 122 123
    }
  }
}

/**
 * Checks if a list of values are being used in actual field values.
 */
124
function _options_values_in_use($entity_type, $field_name, $values) {
125
  if ($values) {
126
    $result = \Drupal::entityQuery($entity_type)
127
      ->condition($field_name . '.value', $values, 'IN')
128 129 130 131 132 133
      ->count()
      ->accessCheck(FALSE)
      ->range(0, 1)
      ->execute();
    if ($result) {
      return TRUE;
134
    }
135 136 137 138
  }

  return FALSE;
}