I have 2 field collections (Parent and child)
Parent Field collection: Test Student Info
machine name: field_test_student_infoChild Field collection: Marks
machine name: field_marks
In parent field collection have 1 field:
Field1: Student Name
machine name: field_student_name
In child field collection have 2 fields:
Field1: English Marks
machine name: field_eng_marksField2: History Marks
Machine name: field_history_marks
I have set field setting "unlimited" to child field collection (Marks). I just want to add new child field collection item programmatically. I have tried below code but it's showing me error:
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\field_collection\Entity\FieldCollectionItem;
function CreateChildFC() {
$node = \Drupal\node\Entity\Node::load(770);
$load = FieldCollectionItem::load(207); // Loading child FC from parent FC i.e Marks
$field_collection_items = $load->field_marks;
$field_collection_item = FieldCollectionItem::create(
[
'field_name' => 'field_marks',
]
);
$field_collection_item->setHostEntity($node);
$field_collection_item->set('field_eng_marks', '89');
$field_collection_item->set('field_history_marks', '75');
$load->field_marks[] = ['field_collection_item' => $field_collection_item];
$node->save();
}
Error
The website encountered an unexpected error. Please try again later.
TypeError: Argument 1 passed to _field_collection_field_item_list_full() must implement interface Drupal\Core\Field\FieldItemListInterface, null given, called in /site/modules/contrib/field_collection/src/Entity/FieldCollectionItem.php on line 333 in _field_collection_field_item_list_full() (line 151 of modules/contrib/field_collection/field_collection.module).