3 namespace Drupal\options\Plugin\Field\FieldType;
5 use Drupal\Core\Field\AllowedTagsXssTrait;
6 use Drupal\Core\Field\FieldDefinitionInterface;
7 use Drupal\Core\Field\FieldItemBase;
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\Core\Form\OptGroup;
10 use Drupal\Core\Session\AccountInterface;
11 use Drupal\Core\TypedData\OptionsProviderInterface;
14 * Plugin base class inherited by the options field types.
16 abstract class ListItemBase extends FieldItemBase implements OptionsProviderInterface {
18 use AllowedTagsXssTrait;
23 public static function defaultStorageSettings() {
25 'allowed_values' => [],
26 'allowed_values_function' => '',
27 ] + parent::defaultStorageSettings();
33 public function getPossibleValues(AccountInterface $account = NULL) {
34 // Flatten options firstly, because Possible Options may contain group
36 $flatten_options = OptGroup::flattenOptions($this->getPossibleOptions($account));
37 return array_keys($flatten_options);
43 public function getPossibleOptions(AccountInterface $account = NULL) {
44 return $this->getSettableOptions($account);
50 public function getSettableValues(AccountInterface $account = NULL) {
51 // Flatten options firstly, because Settable Options may contain group
53 $flatten_options = OptGroup::flattenOptions($this->getSettableOptions($account));
54 return array_keys($flatten_options);
60 public function getSettableOptions(AccountInterface $account = NULL) {
61 $allowed_options = options_allowed_values($this->getFieldDefinition()->getFieldStorageDefinition(), $this->getEntity());
62 return $allowed_options;
68 public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
69 $allowed_options = options_allowed_values($field_definition->getFieldStorageDefinition());
70 $values['value'] = array_rand($allowed_options);
77 public function isEmpty() {
78 return empty($this->value) && (string) $this->value !== '0';
84 public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
85 $allowed_values = $this->getSetting('allowed_values');
86 $allowed_values_function = $this->getSetting('allowed_values_function');
88 $element['allowed_values'] = [
89 '#type' => 'textarea',
90 '#title' => t('Allowed values list'),
91 '#default_value' => $this->allowedValuesString($allowed_values),
93 '#access' => empty($allowed_values_function),
94 '#element_validate' => [[get_class($this), 'validateAllowedValues']],
95 '#field_has_data' => $has_data,
96 '#field_name' => $this->getFieldDefinition()->getName(),
97 '#entity_type' => $this->getEntity()->getEntityTypeId(),
98 '#allowed_values' => $allowed_values,
101 $element['allowed_values']['#description'] = $this->allowedValuesDescription();
103 $element['allowed_values_function'] = [
105 '#title' => t('Allowed values list'),
106 '#markup' => t('The value of this field is being determined by the %function function and may not be changed.', ['%function' => $allowed_values_function]),
107 '#access' => !empty($allowed_values_function),
108 '#value' => $allowed_values_function,
115 * Provides the field type specific allowed values form element #description.
118 * The field type allowed values form specific description.
120 abstract protected function allowedValuesDescription();
123 * #element_validate callback for options field allowed values.
126 * An associative array containing the properties and children of the
127 * generic form element.
129 * The current state of the form for the form this element belongs to.
131 * @see \Drupal\Core\Render\Element\FormElement::processPattern()
133 public static function validateAllowedValues($element, FormStateInterface $form_state) {
134 $values = static::extractAllowedValues($element['#value'], $element['#field_has_data']);
136 if (!is_array($values)) {
137 $form_state->setError($element, t('Allowed values list: invalid input.'));
140 // Check that keys are valid for the field type.
141 foreach ($values as $key => $value) {
142 if ($error = static::validateAllowedValue($key)) {
143 $form_state->setError($element, $error);
148 // Prevent removing values currently in use.
149 if ($element['#field_has_data']) {
150 $lost_keys = array_keys(array_diff_key($element['#allowed_values'], $values));
151 if (_options_values_in_use($element['#entity_type'], $element['#field_name'], $lost_keys)) {
152 $form_state->setError($element, t('Allowed values list: some values are being removed while currently in use.'));
156 $form_state->setValueForElement($element, $values);
161 * Extracts the allowed values array from the allowed_values element.
163 * @param string $string
164 * The raw string to extract values from.
165 * @param bool $has_data
166 * The current field already has data inserted or not.
169 * The array of extracted key/value pairs, or NULL if the string is invalid.
171 * @see \Drupal\options\Plugin\Field\FieldType\ListItemBase::allowedValuesString()
173 protected static function extractAllowedValues($string, $has_data) {
176 $list = explode("\n", $string);
177 $list = array_map('trim', $list);
178 $list = array_filter($list, 'strlen');
180 $generated_keys = $explicit_keys = FALSE;
181 foreach ($list as $position => $text) {
182 // Check for an explicit key.
184 if (preg_match('/(.*)\|(.*)/', $text, $matches)) {
185 // Trim key and value to avoid unwanted spaces issues.
186 $key = trim($matches[1]);
187 $value = trim($matches[2]);
188 $explicit_keys = TRUE;
190 // Otherwise see if we can use the value as the key.
191 elseif (!static::validateAllowedValue($text)) {
192 $key = $value = $text;
193 $explicit_keys = TRUE;
195 // Otherwise see if we can generate a key from the position.
196 elseif (!$has_data) {
197 $key = (string) $position;
199 $generated_keys = TRUE;
205 $values[$key] = $value;
208 // We generate keys only if the list contains no explicit key at all.
209 if ($explicit_keys && $generated_keys) {
217 * Checks whether a candidate allowed value is valid.
219 * @param string $option
220 * The option value entered by the user.
223 * The error message if the specified value is invalid, NULL otherwise.
225 protected static function validateAllowedValue($option) { }
228 * Generates a string representation of an array of 'allowed values'.
230 * This string format is suitable for edition in a textarea.
232 * @param array $values
233 * An array of values, where array keys are values and array values are
237 * The string representation of the $values array:
238 * - Values are separated by a carriage return.
239 * - Each value is in the format "value|label" or "value".
241 protected function allowedValuesString($values) {
243 foreach ($values as $key => $value) {
244 $lines[] = "$key|$value";
246 return implode("\n", $lines);
252 public static function storageSettingsToConfigData(array $settings) {
253 if (isset($settings['allowed_values'])) {
254 $settings['allowed_values'] = static::structureAllowedValues($settings['allowed_values']);
262 public static function storageSettingsFromConfigData(array $settings) {
263 if (isset($settings['allowed_values'])) {
264 $settings['allowed_values'] = static::simplifyAllowedValues($settings['allowed_values']);
270 * Simplifies allowed values to a key-value array from the structured array.
272 * @param array $structured_values
273 * Array of items with a 'value' and 'label' key each for the allowed
277 * Allowed values were the array key is the 'value' value, the value is
280 * @see \Drupal\options\Plugin\Field\FieldType\ListItemBase::structureAllowedValues()
282 protected static function simplifyAllowedValues(array $structured_values) {
284 foreach ($structured_values as $item) {
285 if (is_array($item['label'])) {
286 // Nested elements are embedded in the label.
287 $item['label'] = static::simplifyAllowedValues($item['label']);
289 $values[$item['value']] = $item['label'];
295 * Creates a structured array of allowed values from a key-value array.
297 * @param array $values
298 * Allowed values were the array key is the 'value' value, the value is
302 * Array of items with a 'value' and 'label' key each for the allowed
305 * @see \Drupal\options\Plugin\Field\FieldType\ListItemBase::simplifyAllowedValues()
307 protected static function structureAllowedValues(array $values) {
308 $structured_values = [];
309 foreach ($values as $value => $label) {
310 if (is_array($label)) {
311 $label = static::structureAllowedValues($label);
313 $structured_values[] = [
314 'value' => static::castAllowedValue($value),
318 return $structured_values;
322 * Converts a value to the correct type.
324 * @param mixed $value
330 protected static function castAllowedValue($value) {