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

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

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

10
use Drupal\Core\Field\FieldDefinitionInterface;
11
use Drupal\Core\Field\FieldItemBase;
12
use Drupal\Core\TypedData\DataDefinition;
13 14

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

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

37
  /**
38
   * {@inheritdoc}
39
   */
40 41 42
  public static function propertyDefinitions(FieldDefinitionInterface $field_definition) {
    $properties['value'] = DataDefinition::create('string')
      ->setLabel(t('Text value'));
43

44
    return $properties;
45
  }
46 47 48 49 50 51 52 53 54

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

62 63 64 65 66 67
  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = parent::getConstraints();

68
    if ($max_length = $this->getSetting('max_length')) {
69 70
      $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
      $constraints[] = $constraint_manager->create('ComplexData', array(
71 72 73 74 75 76
        '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)),
          ),
        ),
77 78 79 80 81 82
      ));
    }

    return $constraints;
  }

83
}