ListIntegerItem.php 2.44 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\options\Plugin\Field\FieldType;

5
use Drupal\Core\Field\FieldFilteredMarkup;
6
use Drupal\Core\Field\FieldStorageDefinitionInterface;
7 8 9 10 11 12 13 14 15
use Drupal\Core\TypedData\DataDefinition;

/**
 * Plugin implementation of the 'list_integer' field type.
 *
 * @FieldType(
 *   id = "list_integer",
 *   label = @Translation("List (integer)"),
 *   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 18 19 20 21 22
 *   default_widget = "options_select",
 *   default_formatter = "list_default",
 * )
 */
class ListIntegerItem extends ListItemBase {

23 24 25
  /**
   * {@inheritdoc}
   */
26
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
27
    $properties['value'] = DataDefinition::create('integer')
28 29
      ->setLabel(t('Integer value'))
      ->setRequired(TRUE);
30 31 32 33

    return $properties;
  }

34 35 36
  /**
   * {@inheritdoc}
   */
37
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
38 39 40
    return [
      'columns' => [
        'value' => [
41
          'type' => 'int',
42 43 44 45 46 47
        ],
      ],
      'indexes' => [
        'value' => ['value'],
      ],
    ];
48 49 50 51 52
  }

  /**
   * {@inheritdoc}
   */
53 54 55 56 57 58
  protected function allowedValuesDescription() {
    $description = '<p>' . t('The possible values this field can contain. Enter one value per line, in the format key|label.');
    $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.');
    $description .= '</p>';
59
    $description .= '<p>' . t('Allowed HTML tags in labels: @tags', ['@tags' => FieldFilteredMarkup::displayAllowedTags()]) . '</p>';
60 61
    return $description;
  }
62

63 64 65 66 67 68 69
  /**
   * {@inheritdoc}
   */
  protected static function validateAllowedValue($option) {
    if (!preg_match('/^-?\d+$/', $option)) {
      return t('Allowed values list: keys must be integers.');
    }
70 71
  }

72 73 74 75 76 77 78
  /**
   * {@inheritdoc}
   */
  protected static function castAllowedValue($value) {
    return (int) $value;
  }

79
}