StringItem.php 2.6 KB
Newer Older
1 2
<?php

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

5 6
use Drupal\Component\Utility\Random;
use Drupal\Core\Field\FieldDefinitionInterface;
7
use Drupal\Core\Field\FieldStorageDefinitionInterface;
8
use Drupal\Core\Form\FormStateInterface;
9 10

/**
11
 * Defines the 'string' entity field type.
12
 *
13 14
 * @FieldType(
 *   id = "string",
15 16
 *   label = @Translation("Text (plain)"),
 *   description = @Translation("A field containing a plain string value."),
17
 *   category = @Translation("Text"),
18
 *   default_widget = "string_textfield",
19
 *   default_formatter = "string"
20
 * )
21
 */
22
class StringItem extends StringItemBase {
23

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

34 35 36
  /**
   * {@inheritdoc}
   */
37
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
38 39 40
    return [
      'columns' => [
        'value' => [
41
          'type' => $field_definition->getSetting('is_ascii') === TRUE ? 'varchar_ascii' : 'varchar',
42
          'length' => (int) $field_definition->getSetting('max_length'),
43
          'binary' => $field_definition->getSetting('case_sensitive'),
44 45 46
        ],
      ],
    ];
47 48
  }

49 50 51 52 53 54
  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = parent::getConstraints();

55
    if ($max_length = $this->getSetting('max_length')) {
56
      $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
57 58 59
      $constraints[] = $constraint_manager->create('ComplexData', [
        'value' => [
          'Length' => [
60
            'max' => $max_length,
61 62 63 64
            'maxMessage' => t('%name: may not be longer than @max characters.', ['%name' => $this->getFieldDefinition()->getLabel(), '@max' => $max_length]),
          ],
        ],
      ]);
65 66 67 68 69
    }

    return $constraints;
  }

70 71 72 73 74
  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $random = new Random();
75
    $values['value'] = $random->word(mt_rand(1, $field_definition->getSetting('max_length')));
76 77 78
    return $values;
  }

79 80 81
  /**
   * {@inheritdoc}
   */
82
  public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
83
    $element = [];
84

85
    $element['max_length'] = [
86 87 88 89 90 91 92
      '#type' => 'number',
      '#title' => t('Maximum length'),
      '#default_value' => $this->getSetting('max_length'),
      '#required' => TRUE,
      '#description' => t('The maximum length of the field in characters.'),
      '#min' => 1,
      '#disabled' => $has_data,
93
    ];
94 95 96 97

    return $element;
  }

98
}