UuidItem.php 1.39 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
    return [
28
      '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
    $this->setValue(['value' => $uuid->generate()], $notify);
40
41
    return $this;
  }
42
43
44
45
46
47

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = parent::schema($field_definition);
48
    $schema['unique keys']['value'] = ['value'];
49
50
51
    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
}