ListStringItem.php 2.29 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
use Drupal\Core\TypedData\DataDefinition;

/**
10
 * Plugin implementation of the 'list_string' field type.
11 12
 *
 * @FieldType(
13
 *   id = "list_string",
14 15
 *   label = @Translation("List (text)"),
 *   description = @Translation("This field stores text values from a list of allowed 'value => label' pairs, i.e. 'US States': IL => Illinois, IA => Iowa, IN => Indiana."),
16
 *   category = @Translation("Text"),
17 18 19 20
 *   default_widget = "options_select",
 *   default_formatter = "list_default",
 * )
 */
21
class ListStringItem extends ListItemBase {
22

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

    return $properties;
  }

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

  /**
   * {@inheritdoc}
   */
55 56 57 58 59
  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. 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>';
60
    $description .= '<p>' . t('Allowed HTML tags in labels: @tags', ['@tags' => FieldFilteredMarkup::displayAllowedTags()]) . '</p>';
61 62
    return $description;
  }
63

64 65 66 67
  /**
   * {@inheritdoc}
   */
  protected static function validateAllowedValue($option) {
68
    if (mb_strlen($option) > 255) {
69 70
      return t('Allowed values list: each key must be a string at most 255 characters long.');
    }
71
  }
72

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

80
}