1

I have a problem with field collection and entity reference fields. I have a field collection called 'field_co_intervenant' and i want to add several entities in this field collection and after saved my node. But i got an error with the index i think, because when the node is saved, there is just one reference entity in my field collection. You can see the code here :

$intervenant is the array of my 'nid'.

if(!empty($intervenant)) {
    //Create entity
    $fieldcollection = entity_create('field_collection_item', array('field_name' => 'field__doc_fc_intervenant_tab'));
    //Attach entity
    $fieldcollection->setHostEntity('node', $node);
    //Fill field
    $i = 0;
    foreach ($intervenant as $val) {
        if($val != null) {
            $fieldcollection->field_fc_intervenant_tab[LANGUAGE_NONE][$i]['target_id'] = $val;
            $i++;
        }
    }

    //Save entity
    $fieldcollection->save();
}

How can i save all my values in the field collection and not just one ?

Thanks

3

First be sure that that field in your field collection field setting accept multi value then try save your item with

  $node->field_fc_intervenant_tab['und'][] = array('value' => $field_collection_item->item_id,
    'revision_id' => $field_collection_item->revision_id,);

and finally be something like

if(!empty($intervenant)) {    

    // you should have $node here
      $field_collection_item = NULL;
      $field_collection_item = entity_create('field_collection_item', array('field_name' => ''field__doc_fc_intervenant_tab '));
      $field_collection_item->setHostEntity('node', $node);
      $field_collection_item->save(TRUE);
          foreach ($intervenant as $val) {
             if($val != null) {
      $node->field_fc_intervenant_tab['und'][] = array('value' => $field_collection_item->item_id,
        'revision_id' => $field_collection_item->revision_id,);
}
}
    $fieldcollection->save();
}
  • @Remi you're welcome ;) +1 it :D – Yusef Mohamadi Feb 6 '15 at 6:25

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.