You are here

public function ChangedItem::preSave in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php \Drupal\Core\Field\Plugin\Field\FieldType\ChangedItem::preSave()

Defines custom presave behavior for field values.

This method is called during the process of saving an entity, just before values are written into storage. When storing a new entity, its identifier will not be available yet. This should be used to massage item property values or perform any other operation that needs to happen before values are stored. For instance this is the proper phase to auto-create a new entity for an entity reference field item, because this way it will be possible to store the referenced entity identifier.

Overrides FieldItemBase::preSave

1 call to ChangedItem::preSave()
ChangedTestItem::preSave in core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldType/ChangedTestItem.php
Defines custom presave behavior for field values.
1 method overrides ChangedItem::preSave()
ChangedTestItem::preSave in core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldType/ChangedTestItem.php
Defines custom presave behavior for field values.

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php, line 33
Contains \Drupal\Core\Field\Plugin\Field\FieldType\ChangedItem.

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 = REQUEST_TIME;
  }
  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
      ->hasTranslation($langcode)) {
      $original_value = $original
        ->getTranslation($langcode)
        ->get($this
        ->getFieldDefinition()
        ->getName())->value;
      if ($this->value == $original_value && $entity
        ->hasTranslationChanges()) {
        $this->value = REQUEST_TIME;
      }
    }
  }
}