TimestampItem.php 1.59 KB
Newer Older
1 2 3 4
<?php

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

5
use Drupal\Core\Field\FieldDefinitionInterface;
6
use Drupal\Core\Field\FieldItemBase;
7
use Drupal\Core\Field\FieldStorageDefinitionInterface;
8 9 10 11 12 13 14 15 16
use Drupal\Core\TypedData\DataDefinition;

/**
 * Defines the 'timestamp' entity field type.
 *
 * @FieldType(
 *   id = "timestamp",
 *   label = @Translation("Timestamp"),
 *   description = @Translation("An entity field containing a UNIX timestamp value."),
17
 *   default_widget = "datetime_timestamp",
18 19 20 21 22 23 24 25 26 27 28 29
 *   default_formatter = "timestamp",
 *   constraints = {
 *     "ComplexData" = {
 *       "value" = {
 *         "Range" = {
 *           "min" = "-2147483648",
 *           "max" = "2147483648",
 *         }
 *       }
 *     }
 *   }
 * )
30 31 32 33 34 35
 */
class TimestampItem extends FieldItemBase {

  /**
   * {@inheritdoc}
   */
36
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
37
    $properties['value'] = DataDefinition::create('timestamp')
38 39
      ->setLabel(t('Timestamp value'))
      ->setRequired(TRUE);
40 41 42 43 44 45
    return $properties;
  }

  /**
   * {@inheritdoc}
   */
46
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
47 48 49
    return [
      'columns' => [
        'value' => [
50
          'type' => 'int',
51 52 53
        ],
      ],
    ];
54
  }
55

56 57 58 59 60 61 62 63 64 65
  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    // Pick a random timestamp in the past year.
    $timestamp = \Drupal::time()->getRequestTime() - mt_rand(0, 86400 * 365);
    $values['value'] = $timestamp;
    return $values;
  }

66
}