TextItem.php 2.32 KB
Newer Older
1 2
<?php

3
namespace Drupal\text\Plugin\Field\FieldType;
4

5
use Drupal\Core\Field\FieldStorageDefinitionInterface;
6
use Drupal\Core\Form\FormStateInterface;
7 8 9 10 11 12

/**
 * Plugin implementation of the 'text' field type.
 *
 * @FieldType(
 *   id = "text",
13 14
 *   label = @Translation("Text (formatted)"),
 *   description = @Translation("This field stores a text with a text format."),
15
 *   category = @Translation("Text"),
16 17 18 19 20 21
 *   default_widget = "text_textfield",
 *   default_formatter = "text_default"
 * )
 */
class TextItem extends TextItemBase {

22 23 24
  /**
   * {@inheritdoc}
   */
25
  public static function defaultStorageSettings() {
26
    return [
27
      'max_length' => 255,
28
    ] + parent::defaultStorageSettings();
29 30
  }

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

52 53 54 55
  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
56
    $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
57 58
    $constraints = parent::getConstraints();

59
    if ($max_length = $this->getSetting('max_length')) {
60 61 62
      $constraints[] = $constraint_manager->create('ComplexData', [
        'value' => [
          'Length' => [
63
            'max' => $max_length,
64
            'maxMessage' => t('%name: the text may not be longer than @max characters.', ['%name' => $this->getFieldDefinition()->getLabel(), '@max' => $max_length]),
65
          ],
66 67
        ],
      ]);
68 69 70 71 72
    }

    return $constraints;
  }

73 74 75
  /**
   * {@inheritdoc}
   */
76
  public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
77
    $element = [];
78

79
    $element['max_length'] = [
80 81
      '#type' => 'number',
      '#title' => t('Maximum length'),
82
      '#default_value' => $this->getSetting('max_length'),
83 84 85
      '#required' => TRUE,
      '#description' => t('The maximum length of the field in characters.'),
      '#min' => 1,
86
      '#disabled' => $has_data,
87
    ];
88
    $element += parent::storageSettingsForm($form, $form_state, $has_data);
89 90 91 92 93

    return $element;
  }

}