1<?php
2
3namespace Drupal\options\Plugin\Field\FieldType;
4
5use Drupal\Core\Field\FieldFilteredMarkup;
6use Drupal\Core\Field\FieldStorageDefinitionInterface;
7use Drupal\Core\TypedData\DataDefinition;
8
9/**
10 * Plugin implementation of the 'list_integer' field type.
11 *
12 * @FieldType(
13 *   id = "list_integer",
14 *   label = @Translation("List (integer)"),
15 *   description = @Translation("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."),
16 *   category = @Translation("Number"),
17 *   default_widget = "options_select",
18 *   default_formatter = "list_default",
19 * )
20 */
21class ListIntegerItem extends ListItemBase {
22
23  /**
24   * {@inheritdoc}
25   */
26  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
27    $properties['value'] = DataDefinition::create('integer')
28      ->setLabel(t('Integer value'))
29      ->setRequired(TRUE);
30
31    return $properties;
32  }
33
34  /**
35   * {@inheritdoc}
36   */
37  public static function schema(FieldStorageDefinitionInterface $field_definition) {
38    return [
39      'columns' => [
40        'value' => [
41          'type' => 'int',
42        ],
43      ],
44      'indexes' => [
45        'value' => ['value'],
46      ],
47    ];
48  }
49
50  /**
51   * {@inheritdoc}
52   */
53  protected function allowedValuesDescription() {
54    $description = '<p>' . t('The possible values this field can contain. Enter one value per line, in the format key|label.');
55    $description .= '<br/>' . t('The key is the stored value, and must be numeric. The label will be used in displayed values and edit forms.');
56    $description .= '<br/>' . t('The label is optional: if a line contains a single number, it will be used as key and label.');
57    $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.');
58    $description .= '</p>';
59    $description .= '<p>' . t('Allowed HTML tags in labels: @tags', ['@tags' => FieldFilteredMarkup::displayAllowedTags()]) . '</p>';
60    return $description;
61  }
62
63  /**
64   * {@inheritdoc}
65   */
66  protected static function validateAllowedValue($option) {
67    if (!preg_match('/^-?\d+$/', $option)) {
68      return t('Allowed values list: keys must be integers.');
69    }
70  }
71
72  /**
73   * {@inheritdoc}
74   */
75  protected static function castAllowedValue($value) {
76    return (int) $value;
77  }
78
79}
80