How to fix "Unable to save a field collection item without a valid reference to a host entity" error? I programmatically created a series of custom content entities which contain field collections. My site had an execution timeout error in the middle of entity creation and saving.

I can not delete some of these entities. Any attempt is met with:


  The website encountered an unexpected error. Please try again later.
  
  Drupal\Core\Entity\EntityStorageException: Unable to save a field
  collection item without a valid reference to a host entity in
  Drupal\Core\Entity\Sql\SqlContentEntityStorage->delete() (line 718 of
  core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).


I need to be able to delete these host entities. They are still showing up in my entity list. I can edit and save them, I just cannot delete them.

How can I delete the host entities?
Sorry for the late reply but your question is a bit confusing and I would like to clarify the mentioned issue (message). Did you use ->setHostEntity($obj) at creation of the FieldCollection? I think that you created "ghost" fieldCollections. Have a look in DB if they was added there and you don't see the new FieldCollection at HostEntity in back end.

In my case, i was loading a FieldCollection Item which also did not have the HostEntity set and was struggling with the same Error Message (therefor the explanation). Later I figured out that the following procedure is correct - mention the saving of the HostEntity of the FieldCollection:

use Drupal\field_collection\Entity\FieldCollectionItem;

$fieldCollectionObj = FieldCollectionItem::load($fcId);
if($fieldCollectionObj-&gt;hasField('field_my_user_fc_field')) {
    $userObj = \Drupal\user\Entity\User::load(\Drupal::currentUser()-&gt;id());
    $fieldCollectionObj-&gt;set('field_my_user_fc_field', 'my new value');
    $userObj-&gt;save();
}