UuidItem.php 1.4 KB
Newer Older
1 2
<?php

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

5
use Drupal\Core\Field\FieldStorageDefinitionInterface;
6
use Drupal\Core\Field\FieldDefinitionInterface;
7

8
/**
9
 * Defines the 'uuid' entity field type.
10 11 12
 *
 * The field uses a newly generated UUID as default value.
 *
13 14 15
 * @FieldType(
 *   id = "uuid",
 *   label = @Translation("UUID"),
16
 *   description = @Translation("An entity field containing a UUID."),
17 18
 *   no_ui = TRUE,
 *   default_formatter = "string"
19 20 21 22
 * )
 */
class UuidItem extends StringItem {

23 24 25
  /**
   * {@inheritdoc}
   */
26
  public static function defaultStorageSettings() {
27 28
    return array(
      'max_length' => 128,
29
      'is_ascii' => TRUE,
30
    ) + parent::defaultStorageSettings();
31 32
  }

33 34 35 36 37
  /**
   * {@inheritdoc}
   */
  public function applyDefaultValue($notify = TRUE) {
    // Default to one field item with a generated UUID.
38
    $uuid = \Drupal::service('uuid');
39 40 41
    $this->setValue(array('value' => $uuid->generate()), $notify);
    return $this;
  }
42 43 44 45 46 47 48 49 50 51

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = parent::schema($field_definition);
    $schema['unique keys']['value'] = array('value');
    return $schema;
  }

52 53 54 55 56 57 58 59
  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $values['value'] = \Drupal::service('uuid')->generate();
    return $values;
  }

60
}