You are here

public function RadioactivityReferenceItem::preSave in Radioactivity 4.0.x

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 EntityReferenceItem::preSave

File

src/Plugin/Field/FieldType/RadioactivityReferenceItem.php, line 166

Class

RadioactivityReferenceItem
Plugin implementation of the Radioactivity Reference field type.

Namespace

Drupal\radioactivity\Plugin\Field\FieldType

Code

public function preSave() {
  $needsSave = FALSE;
  $requestTime = \Drupal::time()
    ->getRequestTime();

  // New entity: Store the energy value in the entity. Saving the entity is
  // handled by parent::preSave.
  if ($this
    ->hasNewEntity()) {
    $this->entity
      ->setEnergy($this->energy);
    $this->entity
      ->setTimestamp($requestTime);
  }
  elseif ($this->energy != $this->initial_energy) {
    $this->entity
      ->setEnergy($this->energy);
    $this->entity
      ->setTimestamp($requestTime);
    $needsSave = TRUE;
  }

  // Keep the language code of the radioactivity entity in sync with the
  // language code of the host.
  if ($this
    ->getLangcode() !== $this->entity->getLangcode) {
    $this->entity
      ->setLangcode($this
      ->getLangcode());
    if (!$this
      ->hasNewEntity()) {
      $needsSave = TRUE;
    }
  }
  if ($needsSave) {
    $this->entity
      ->save();
  }
  parent::preSave();
}