I have 1 field collection

Field collection: CKT Info child2
machine name: field_ckt_info_child2

In that have 2 fields:

Field1: English CKT child2
machine name: field_eng

Field2: Maths CKT Child2
Machine name: field_maths_ckt_child2

I have set field setting "unlimited" to this field collection. Now I just want to add new field collection item in existing Field collection(CKT Info child2) programmatically. I have tried below code but it's not creating new field collection item. FC Image

function createFC()  {
   $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_maths_ckt_child2'));
   $field_collection_item->set('field_maths_ckt_child2', "SET SUCCESS");

1 Answer 1


You can try code:


use Drupal\field_collection\Entity\FieldCollectionItem;
use Drupal\node\Entity\Node;


$node = Node::load(1);

$field_collection_items = $node->field_ckt_info_child2;
$fieldCollectionList = $field_collection_items;
if (count($fieldCollectionList)) {
  $field_collection_item = FieldCollectionItem::load($fieldCollectionList[0]->value);
else {
  //create new fieldconlection
  $field_collection_item = FieldCollectionItem::create(
      'field_name' => 'field_ckt_info_child2',
  $field_collection_item->set('field_eng', 'HELLO');
  $field_collection_item->set('field_maths_ckt_child2', 'WORLD');
  $node->field_ckt_info_child2[] = ['field_collection_item' => $field_collection_item];

  • To make it more explicit: The error in the code used from the OP is not initializing $node before using it.
    – apaderno
    Commented Oct 2, 2019 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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