You are here

public function EntityReferenceItem::preSave in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::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 EntityReferenceItem::preSave()
ImageItem::preSave in core/modules/image/src/Plugin/Field/FieldType/ImageItem.php
Defines custom presave behavior for field values.
1 method overrides EntityReferenceItem::preSave()
ImageItem::preSave in core/modules/image/src/Plugin/Field/FieldType/ImageItem.php
Defines custom presave behavior for field values.

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php, line 263

Class

EntityReferenceItem
Defines the 'entity_reference' entity field type.

Namespace

Drupal\Core\Field\Plugin\Field\FieldType

Code

public function preSave() {
  if ($this
    ->hasNewEntity()) {

    // Save the entity if it has not already been saved by some other code.
    if ($this->entity
      ->isNew()) {
      $this->entity
        ->save();
    }

    // Make sure the parent knows we are updating this property so it can
    // react properly.
    $this->target_id = $this->entity
      ->id();
  }
  if (!$this
    ->isEmpty() && $this->target_id === NULL) {
    $this->target_id = $this->entity
      ->id();
  }
}