Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By zorax on
Hi,
I need to to put values from a node in a collection field placed in a form.
My problem appears when I need to create 'new item' of the field collection.
For example, in my node I have two items of a collection, I need to put two item in the form with the value of the node. When the user open the form, there is only one item.
My code is working, I can see two items, the values are OK, but when I save the form, the new item of the collection created are not saved in the node.
$loaded_node = node_load($record->nid );
//if the node exists and the data of the form are empty, then create the list of the collection value
if ((isset($loaded_node) && (empty($form['field_onglet4_fiche_analyse']['und'][0]['field_fiche_intitule']['und'][0]['value']['#default_value'])))) {
$wrapper = entity_metadata_wrapper('node', $loaded_node);
$item_count = -1;
foreach ($wrapper->field_experiences as $i) {
$item_count++;
// add new item if needed
if ($item_count>0) {
// create the field_collection item
// $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_onglet4_fiche_analyse'));
//associate it with the node array
// $field_collection_item->setHostEntity('node', $form['#node']);//logically I read to put setHostEntity('node', $node) but I'm working in a form
$field_collection_clone = $form['field_onglet4_fiche_analyse']['und'][0];
$form['field_onglet4_fiche_analyse']['und'][$item_count] = $field_collection_clone;
}
//prepopulate the fields
$form['field_onglet4_fiche_analyse']['und'][$item_count]['field_fiche_intitule']['und'][0]['value']['#default_value'] =$i->field_exp_emploi->value();
$form['field_onglet4_fiche_analyse']['und'][$item_count]['field_fiche_structure']['und'][0]['value']['#default_value'] =$i->field_exp_lieu->value();
foreach ($i->field_exp_taches as $j) {
$infos_onglet2.=$j->value();
$infos_onglet2.=' , ';
$form['field_onglet4_fiche_analyse']['und'][$item_count]['field_fiche_missions']['und'][0]['#default_value'] .=$j->value().' <br> ';
}
}
Thank you for your help !