function ChangedItem::preSave

Same name in other branches
  1. 9 core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php \Drupal\Core\Field\Plugin\Field\FieldType\ChangedItem::preSave()
  2. 8.9.x core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php \Drupal\Core\Field\Plugin\Field\FieldType\ChangedItem::preSave()
  3. 10 core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php \Drupal\Core\Field\Plugin\Field\FieldType\ChangedItem::preSave()

Overrides FieldItemBase::preSave

1 call to ChangedItem::preSave()
ChangedTestItem::preSave in core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldType/ChangedTestItem.php
1 method overrides ChangedItem::preSave()
ChangedTestItem::preSave in core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldType/ChangedTestItem.php

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php, line 32

Class

ChangedItem
Defines the 'changed' entity field type.

Namespace

Drupal\Core\Field\Plugin\Field\FieldType

Code

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();
        if (!$entity instanceof SynchronizableInterface || !$entity->isSyncing()) {
            
            /** @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();
                }
            }
        }
    }
}

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