2

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:

<?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?

3

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.

<?php

// […]

$nodeId = 123;

/** @var EntityStorageInterface $entityStorage */
$entityStorage = Drupal::entityTypeManager()->getStorage('node');

$node = $entityStorage->load($nodeId);
$node->body = 'Body Update: ' . date('c');

/** @var Drupal\Core\Field\FieldItemList $fieldItemList */
$fieldItemList = $node->field_test_field_collection;

// Reuse existing Field Collection.
if (count($fieldItemList))
{
    /** @var \Drupal\field_collection\Plugin\Field\FieldType\FieldCollection $fieldCollection */
    $fieldCollection = $fieldItemList[0];
    $fieldCollectionItem = FieldCollectionItem::load($fieldCollection->value);
}

// Create new Field Collection.
else
{
    $fieldCollectionItem = FieldCollectionItem::create([
        'field_name' => 'field_test_field_collection',
    ]);

    $fieldCollectionItem->setHostEntity($node);

    $node->field_test_field_collection[] = [
        'field_collection_item' => $fieldCollectionItem,
    ];
}

$fieldCollectionItem->set('field_text', 'Last Update: ' . date('c'));

$node->save();

Deleting an existing collection is as simple as: fieldCollectionItem->delete();

Please have a look at the source code of the unit test class Drupal\field_collection\Tests\FieldCollectionBasicTestCase for more information.

-2

Check the below link,

https://www.drupal.org/node/2683787

That may help you in your case.

  • Thank you for the link. Unfortunately, it didn't help me to find the answer. The snippet of drupal.org user smaz doesn't save the collections on my system. – Rayne Jul 2 '16 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.