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
- Machine name:
The field collection field_test_field_collection
has only one field:
- Example Text
- Machine name:
field_text
- Type:
text
- Machine name:
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
:
<?php
namespace Drupal\my_module\Controller;
use Drupal;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityStorageInterface;
class FieldCollectionTestController extends ControllerBase {
/**
* @return array
*/
public function content() {
$nodeId = 1402;
/** @var EntityStorageInterface $entityStorage */
$entityStorage = Drupal::entityTypeManager()->getStorage('node');
$node = $entityStorage->load($nodeId);
// Dump.
{
ob_start();
var_dump($node->field_test_field_collection->field_text);
$dump = ob_get_clean();
}
// Update node and field collection.
{
$exampleText = "Updated at " . time();
$node->body = $exampleText;
$node->field_test_field_collection->field_text = $exampleText;
$node->save();
}
$response = [
'#theme' => 'item_list',
'#title' => 'Dumps',
'#items' => [
[
'#type' => 'markup',
'#markup' => $dump,
],
],
];
return $response;
}
}
The value of $dump
is null
.
Question
How do you insert, update and delete Field Collections in Drupal 8?