Skip to content

Instantly share code, notes, and snippets.

@init90
Created September 24, 2018 09:58
Show Gist options
  • Select an option

  • Save init90/7bee7d16d26c59954a994628827ff07d to your computer and use it in GitHub Desktop.

Select an option

Save init90/7bee7d16d26c59954a994628827ff07d to your computer and use it in GitHub Desktop.
Drupal 8, attach field collection to some entity. In this example to commerce product entity.
use Drupal\commerce_product\Entity\Product;
use Drupal\field_collection\Entity\FieldCollectionItem;
$product = Product::load(34);
$fc_item = FieldCollectionItem::create([
'field_name' => 'ENTITY_FIELD_COLLECTION_FIELD',
]);
$fc_item->set('field_horizontal_position', $horizontal_pos);
$fc_item->set('field_vertical_position', $vertical_pos);
$fc_item->setHostEntity($product, FALSE);
$product->ENTITY_FIELD_COLLECTION_FIELD[] = [
'field_collection_item' => $fc_item,
];
$product->save();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment