StringItem.php 2.6 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\Form\FormStateInterface;
14 15

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

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

37 38 39
  /**
   * {@inheritdoc}
   */
40
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
41 42 43 44
    return array(
      'columns' => array(
        'value' => array(
          'type' => 'varchar',
45
          'length' => (int) $field_definition->getSetting('max_length'),
46
          'binary' => $field_definition->getSetting('case_sensitive'),
47 48 49 50 51
        ),
      ),
    );
  }

52 53 54 55 56 57
  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = parent::getConstraints();

58
    if ($max_length = $this->getSetting('max_length')) {
59 60
      $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
      $constraints[] = $constraint_manager->create('ComplexData', array(
61 62 63 64 65 66
        '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)),
          ),
        ),
67 68 69 70 71 72
      ));
    }

    return $constraints;
  }

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

82 83 84
  /**
   * {@inheritdoc}
   */
85
  public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    $element = array();

    $element['max_length'] = array(
      '#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,
    );

    return $element;
  }

101
}