You are here

public function FieldCollectionItem::save in Field collection 8.3

Same name and namespace in other branches
  1. 8 src/Entity/FieldCollectionItem.php \Drupal\field_collection\Entity\FieldCollectionItem::save()

Save the field collection item.

By default, always save the host entity, so modules are able to react upon changes to the content of the host and any 'last updated' dates of entities get updated.

For creating an item a host entity has to be specified via setHostEntity() before this function is invoked. For the link between the entities to be fully established, the host entity object has to be updated to include a reference on this field collection item during saving. So do not skip saving the host for creating items.

Parameters

$skip_host_save: (internal) If TRUE is passed, the host entity is not saved automatically and therefore no link is created between the host and the item or revision updates might be skipped. Use with care.

Overrides EntityBase::save

File

src/Entity/FieldCollectionItem.php, line 153

Class

FieldCollectionItem
Defines the field collection item entity class.

Namespace

Drupal\field_collection\Entity

Code

public function save($skip_host_save = FALSE) {

  /* TODO: Need this.
     // Make sure we have a host entity during creation.
     if (!empty($this->is_new) && !(isset($this->hostEntityId) || isset($this->hostEntity) || isset($this->hostEntityRevisionId))) {
       throw new Exception("Unable to create a field collection item without a given host entity.");
     }
     */

  // Only save directly if we are told to skip saving the host entity. Else,
  // we always save via the host as saving the host might trigger saving
  // field collection items anyway (e.g. if a new revision is created).
  if ($skip_host_save) {
    return parent::save();
  }
  else {
    $host_entity = $this
      ->getHost();
    if (!$host_entity) {
      throw new \Exception('Unable to save a field collection item without a valid reference to a host entity');
    }

    /* TODO: Need this.
       // If this is creating a new revision, also do so for the host entity.
       if (!empty($this->revision) || !empty($this->is_new_revision)) {
         $host_entity->revision = TRUE;
         if (!empty($this->default_revision)) {
           entity_revision_set_default($this->hostEntityType, $host_entity);
         }
       }
       */

    // Set the host entity reference, so the item will be saved with the host.
    // @see field_collection_field_presave()
    $delta = $this
      ->getDelta();
    $value = $host_entity->{$this
      ->bundle()}
      ->getValue();
    if (isset($delta)) {
      $value[$delta] = [
        'entity' => $this,
      ];
    }
    else {
      $value[] = [
        'entity' => $this,
      ];
    }
    $host_entity->{$this
      ->bundle()}
      ->setValue($value);
    return $host_entity
      ->save();
  }
}