Could someone please provide an example on how to create the fields and add values?

Example: Map (node) has unlimited areas (field collection field). Each area has unlimited layers (field collection field). The area fc. have normal fields and the layer fc. The layer fc. only have normal fields.

Creating and attaching an fc. to a node is fine, but I can't work out how to add another fc. to that fc..
I assume the 2nd fc. should use the 1st fc. id as HostEntity?!

Any ideas, suggestions are welcome. Thanks a lot.

Comments

Greg Varga’s picture

So it turned out that the solution was very simple:

1) Create the base node (Map) and save it using node_save() -> $map_node

2) Create the first field collection (Area)

<?php
$area_field_collection_item = entity_create('field_collection_item', array(
      'field_name'        => 'field_area',
      'field_coordinates' => array(LANGUAGE_NONE => array(array('value' =>1))),
));
$area_field_collection_item->setHostEntity('node', $map_node);
$area_field_collection_item->save();    
?>

The Area fc. contains another fc. called Layers, but for now, we can ignore that. Add the required values, set the HostEntity, which is the $map_node and save the fc.

3) Create the second field collection (Layers)

<?php
$layer_field_collection_item = entity_create('field_collection_item', array(
      'field_name'           => 'field_layers',
      'field_layer_id'       => array(LANGUAGE_NONE => array(array('value' =>1))),
      [ADD ANY OTHER FIELDS YOU HAVE ON LAYER],        
));
$layer_field_collection_item->setHostEntity('field_collection_item', $area_field_collection_item);
$layer_field_collection_item->save();  
?>

This is pretty much the same as the previous code, but the HostEntity is pointing to the Area fc. and the HostEntity type is "field_collection_item"

Once everything is saved, you are good to go. Good luck.

Greg Varga’s picture

Status: Active » Fixed

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.