StringItem.php 2.56 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 11
use Drupal\Component\Utility\Random;
use Drupal\Core\Field\FieldDefinitionInterface;
12
use Drupal\Core\Field\FieldStorageDefinitionInterface;
13
use Drupal\Core\Field\FieldItemBase;
14
use Drupal\Core\StringTranslation\TranslationWrapper;
15
use Drupal\Core\TypedData\DataDefinition;
16 17

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

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

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

49
    return $properties;
50
  }
51 52 53 54

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

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

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

    return $constraints;
  }

88 89 90 91 92 93 94 95 96 97
  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $random = new Random();
    $max = $field_definition->getSetting('max_length');
    $values['value'] = $random->word(mt_rand(1, $max));
    return $values;
  }

98
}