I would like to insert and update Field Collection values. I'm using Drupal 8 with field_collection 8.x-1.0-alpha1.

Setup

I have created a new content type test_content_type with the following fields:

Title

Body

…

Test Field Collection

Machine name: field_test_field_collection

Type: field collection

The field collection field_test_field_collection has only one field:

Example Text

Machine name: field_text

Type: text

The Problem

I also created a node with values, for instance Lorem Ipsum as field_text.value, but I don't know how to read and define the value programmatically. I tried the following, which updates body but doesn't update field_text:

2 Answers
2

The following snippet (compatible with field_collection 8.x-1.0-alpha1) reuses an existing FieldCollectionItem or creates a new one on demand. The last few lines show how to modify fields inside the FieldCollectionItem.

If one has a field collection with a different name, then it should be enough to replace all occurrences of field_test_field_collection with the custom field collection's machine name.