ChangedItem.php

Same filename and directory in other branches
  1. 9 core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php
  2. 8.9.x core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php
  3. 11.x core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php

Namespace

Drupal\Core\Field\Plugin\Field\FieldType

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php

View source
<?php

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

use Drupal\Core\Field\Attribute\FieldType;
use Drupal\Core\Field\ChangedFieldItemList;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Defines the 'changed' entity field type.
 *
 * Based on a field of this type, entity types can easily implement the
 * EntityChangedInterface.
 *
 * @see \Drupal\Core\Entity\EntityChangedInterface
 */
class ChangedItem extends CreatedItem {
  
  /**
   * {@inheritdoc}
   */
  public function preSave() {
    parent::preSave();
    // Set the timestamp to request time if it is not set.
    if (!$this->value) {
      $this->value = \Drupal::time()->getRequestTime();
    }
    else {
      // 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
      // \Drupal\content_translation\ContentTranslationMetadataWrapperInterface::setChangedTime().
      /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
      $entity = $this->getEntity();
      /** @var \Drupal\Core\Entity\ContentEntityInterface $original */
      $original = $entity->original;
      $langcode = $entity->language()
        ->getId();
      if (!$entity->isNew() && $original && $original->hasTranslation($langcode)) {
        $original_value = $original->getTranslation($langcode)
          ->get($this->getFieldDefinition()
          ->getName())->value;
        if ($this->value == $original_value && $entity->hasTranslationChanges()) {
          $this->value = \Drupal::time()->getRequestTime();
        }
      }
    }
  }

}

Classes

Title Deprecated Summary
ChangedItem Defines the 'changed' entity field type.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.