StringItem.php 2.2 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\Field\Plugin\Field\FieldType\StringItem.
6 7
 */

8
namespace Drupal\Core\Field\Plugin\Field\FieldType;
9

10
use Drupal\Core\Field\FieldStorageDefinitionInterface;
11
use Drupal\Core\Field\FieldItemBase;
12
use Drupal\Core\StringTranslation\TranslationWrapper;
13
use Drupal\Core\TypedData\DataDefinition;
14 15

/**
16
 * Defines the 'string' entity field type.
17
 *
18 19 20
 * @FieldType(
 *   id = "string",
 *   label = @Translation("String"),
21
 *   description = @Translation("An entity field containing a string value."),
22
 *   no_ui = TRUE,
23 24
 *   default_widget = "string",
 *   default_formatter = "string"
25
 * )
26 27 28
 */
class StringItem extends FieldItemBase {

29 30 31 32 33 34 35 36 37
  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'max_length' => 255,
    ) + parent::defaultSettings();
  }

38
  /**
39
   * {@inheritdoc}
40
   */
41
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
42 43
    // This is called very early by the user entity roles field. Prevent
    // early t() calls by using the TranslationWrapper.
44
    $properties['value'] = DataDefinition::create('string')
45
      ->setLabel(new TranslationWrapper('Text value'));
46

47
    return $properties;
48
  }
49 50 51 52

  /**
   * {@inheritdoc}
   */
53
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
54 55 56 57
    return array(
      'columns' => array(
        'value' => array(
          'type' => 'varchar',
58
          'length' => (int) $field_definition->getSetting('max_length'),
59 60 61 62 63 64
          'not null' => FALSE,
        ),
      ),
    );
  }

65 66 67 68 69 70
  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = parent::getConstraints();

71
    if ($max_length = $this->getSetting('max_length')) {
72 73
      $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
      $constraints[] = $constraint_manager->create('ComplexData', array(
74 75 76 77 78 79
        'value' => array(
          'Length' => array(
            'max' => $max_length,
            'maxMessage' => t('%name: may not be longer than @max characters.', array('%name' => $this->getFieldDefinition()->getLabel(), '@max' => $max_length)),
          ),
        ),
80 81 82 83 84 85
      ));
    }

    return $constraints;
  }

86
}