/** * Provides the field collection item submission form. * * @param \Drupal\field_collection\Entity\FieldCollection $field_collection * The field_collection entity for the field collection item. * * @param $host_type * The type of the entity hosting the field collection item. * * @param $host_id * The id of the entity hosting the field collection item. * * @return array * A field collection item submission form. * * TODO: additional fields */ public function add(FieldCollection $field_collection, $host_type, $host_id) { $host = entity_load($host_type, $host_id); if (_field_collection_field_item_list_full($host->{$field_collection->id()})) { drupal_set_message(t('This field is already full.'), 'error'); return array('#markup' => 'Can not add to an already full field.'); } else { $field_collection_item = $this->entityManager()->getStorage('field_collection_item')->create(array('field_name' => $field_collection->id(), 'host_type' => $host_type, 'revision_id' => 0)); $form = $this->entityFormBuilder()->getForm($field_collection_item); return $form; } }
/** * {@inheritdoc} */ 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()}[] = array('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.')); } }