Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By anoopmohan on
Is there anyway to delete field collections programmatically in Drupal 8? I have created a field collections and attached it to the user entity in the following method.
$user_id = \Drupal::currentUser()->getAccount()->id();
$user = User::load($user_id);
$fc = FieldCollectionItem::create(array(
"field_name" => "field_hobbies",
));
$fc->set('field_hobby_name', 'Watch TV');
$fc->setHostEntity($user);
It works fine and the field collection created successfully. Now, I want to delete this field collection. That means, I want to delete the hobby from the user. Is there any way for doing this?
Thanks
Comments
Delete field collections programmatically
Here is the answer:
$user = User::load($user_id);
$storage = \Drupal::entityTypeManager()->getStorage('field_collection_item');
$fc_items = [];
foreach ($user->get('field_hobbies') as $item) {
$fc_items[] = $item->value;
}
if (!empty($fc_items)) {
$items = $storage->loadMultiple($fc_items);
$storage->delete(items);
$user->set('field_hobbies', array());
}
$user->save();