How do I properly delete a field collection? I added a new field (houses) to user accounts. This field is a list of a collection fields. 

I need to list all the fields in a user field collection (I can via the FieldCollectionItem::loadMultiple(array(12,45,...)) and remove all of them. 

This is my code:

$array_of_fieldcollection = get_array_of_fieldcollection_of_user();

$fieldscollection = FieldCollectionItem::loadMultiple($array_of_fieldcollection);

foreach($fieldscollection as $fieldcollection){
  $fieldcollection-&gt;delete();
}


When I execute it and go to the user profile edit page, I get this error: 


  The website encountered an unexpected error. Please try again later.
  More detail in the Apache log.
  
  TypeError: Argument 1 passed to Drupal\Core\Entity\Entity\EntityFormDisplay::buildForm() must implement interface Drupal\Core\Entity\FieldableEntityInterface, null given, called in /var/www/www.orlengine.com/modules/contrib/old_field_collection/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php on line 71 in drupaldirectory/core/lib/Drupal/Core/Entity/Entity/EntityFormDisplay.php on line 159, referer: https://192.168.1.45/user/9


Isn't my code the proper way to delete all the field of a field collection?
The code you've shared is correct. The problem is that when we attach a Field Collection field to "User" entity the Host Entity of Field Collection is not set.

Because of which when we delete a Field Collection Entity programmatically the Host Entity field value (i.e. User in this case) is not updated with deletion. This causes Drupal to load Field collection which doesn't exists in system.

Rewriting the deletion code below:

use Drupal\field_collection\Entity\FieldCollectionItem;

// Load all field collections to delete.
$field_collections = FieldCollectionItem::loadMultiple(array(1, 2));
foreach($field_collections as $field_collection){
  // Delete field collection.
  $field_collection-&gt;delete();
}