You are here

public function FieldCollectionItem::setHostEntity in Field collection 8

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

Sets the host entity. Only possible during creation of a item.

Parameters

\Drupal\Core\Entity\ContentEntityInterface $entity: The host entity to add the the field collection item to.

$create_link: (optional) Whether a field-item linking the host entity to the field collection item should be created. Defaults to TRUE.

Overrides FieldCollectionItemInterface::setHostEntity

File

src/Entity/FieldCollectionItem.php, line 288

Class

FieldCollectionItem
Defines the field collection item entity class.

Namespace

Drupal\field_collection\Entity

Code

public function setHostEntity($entity, $create_link = TRUE) {
  if ($this
    ->isNew()) {
    $this->host_type = $entity
      ->getEntityTypeId();
    $this->host_id = $entity
      ->id();
    $this->host_entity = $entity;

    // If the host entity is not saved yet, set the id to FALSE. So
    // fetchHostDetails() does not try to load the host entity details.
    if (!isset($this->host_id)) {
      $this->host_id = FALSE;
    }

    /*
    // We are create a new field collection for a non-default entity, thus
    // set archived to TRUE.
    if (!entity_revision_is_default($entity_type, $entity)) {
      $this->hostEntityId = FALSE;
      $this->archived = TRUE;
    }
    */

    // Add the field collection item to its host.
    if ($create_link) {
      if (_field_collection_field_item_list_full($entity->{$this
        ->bundle()})) {
        drupal_set_message(t('Field is already full.'), 'error');
      }
      else {
        $entity->{$this
          ->bundle()}[] = [
          'field_collection_item' => $this,
        ];
        $entity
          ->save();
      }
    }
  }
  else {
    throw new \Exception(t('The host entity may be set only during creation of a field collection item.'));
  }
}