Drupal - How to properly delete a field collection?
I ran into a similar use case where I wanted to map some data into a field collection during hook_feeds_presave() since the source structure was too complex for Feeds. I found that entity_delete_multiple() removed the field collection items, but when I edited the node, there were still a bunch of empty field collection there. Unsetting and deleting did the trick, which I found here: https://drupal.stackexchange.com/a/31820/2762
If the feeds source has changed, I delete all field collection items and recreate. Hope this is helpful.
foreach ($node->field_international_activity[LANGUAGE_NONE] as $key => $value) {
// Build array of field collection values.
$field_collection_item_values[] = $value['value'];
// Unset them.
unset($node->field_international_activity[LANGUAGE_NONE][$key]);
}
// Delete field collection items.
entity_delete_multiple('field_collection_item', $field_collection_item_values);
The best way to do this now is call $field_collection->delete()
and that will handle everything.
<?php
/**
* Deletes the field collection item and the reference in the host entity.
*/
public function delete() {
parent::delete();
$this->deleteHostEntityReference();
}
/**
* Deletes the host entity's reference of the field collection item.
*/
protected function deleteHostEntityReference() {
$delta = $this->delta();
if ($this->item_id && isset($delta)) {
unset($this->hostEntity->{$this->field_name}[$this->langcode][$delta]);
entity_save($this->hostEntityType, $this->hostEntity);
}
}
?>