Search code examples
drupal-7

Dynamically add a "Field Collection" in Drupal 7 by script?


I want to add a "field collection" dynamically. But I'm not familiar with Field API or Entity API. New Entity API in Drupal is very poorly documented.

Here is my code, until now:

$node = node_load(1);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_book_text'));
$field_collection_item->setHostEntity('node', $node);

// Adding fields to field_collection

$field_collection_item.save();

"Field Collection" module use function "entity_form_submit_build_entity" which I cannot use because there is no form in my case.

I would appreciate if you can tell me how can I add fields?


Solution

  • Based on some code I used in a live project:

    // Create and save research field collection for node.
    $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_article_references'));
    $field_collection_item->setHostEntity('node', $node);
    $field_collection_item->field_reference_text[$node->language][]['value'] = 'ABCD';          
    $field_collection_item->field_reference_link[$node->language][]['value'] = 'link-val';
    $field_collection_item->field_reference_order[$node->language][]['value'] = 1;
    $field_collection_item->save();