ChangedItem.php 1.94 KB
Newer Older
1 2 3 4 5 6 7
<?php

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

/**
 * Defines the 'changed' entity field type.
 *
8 9 10
 * Based on a field of this type, entity types can easily implement the
 * EntityChangedInterface.
 *
11 12 13 14
 * @FieldType(
 *   id = "changed",
 *   label = @Translation("Last changed"),
 *   description = @Translation("An entity field containing a UNIX timestamp of when the entity has been last updated."),
15
 *   no_ui = TRUE,
16
 *   default_widget = "datetime_timestamp",
17
 *   default_formatter = "timestamp",
18
 *   list_class = "\Drupal\Core\Field\ChangedFieldItemList"
19
 * )
20 21
 *
 * @see \Drupal\Core\Entity\EntityChangedInterface
22 23 24 25 26 27 28 29
 */
class ChangedItem extends CreatedItem {

  /**
   * {@inheritdoc}
   */
  public function preSave() {
    parent::preSave();
30 31 32

    // Set the timestamp to request time if it is not set.
    if (!$this->value) {
33
      $this->value = REQUEST_TIME;
34 35
    }
    else {
36 37 38 39 40
      // On an existing entity translation, the changed timestamp will only be
      // set to the request time automatically if at least one other field value
      // of the entity has changed. This detection does not run on new entities
      // and will be turned off if the changed timestamp is set manually before
      // save, for example during migrations or by using
41
      // \Drupal\content_translation\ContentTranslationMetadataWrapperInterface::setChangedTime().
42
      /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
43
      $entity = $this->getEntity();
44 45 46
      /** @var \Drupal\Core\Entity\ContentEntityInterface $original */
      $original = $entity->original;
      $langcode = $entity->language()->getId();
47
      if (!$entity->isNew() && $original && $original->hasTranslation($langcode)) {
48 49
        $original_value = $original->getTranslation($langcode)->get($this->getFieldDefinition()->getName())->value;
        if ($this->value == $original_value && $entity->hasTranslationChanges()) {
50
          $this->value = REQUEST_TIME;
51 52 53
        }
      }
    }
54 55 56
  }

}