Skip to content

Instantly share code, notes, and snippets.

@mrconnerton
Created March 13, 2012 21:28
Show Gist options
  • Save mrconnerton/2031747 to your computer and use it in GitHub Desktop.
Save mrconnerton/2031747 to your computer and use it in GitHub Desktop.
How to programtically save a node with field collections
<?php
// Lets just pretend your content type is "Event" with machine name "event"
$node = new stdClass();
$node->type = 'event';
node_object_prepare($node);
$node->title = "My event title";
$node->language = LANGUAGE_NONE;
// Add your node data here. You can add fields like:
$node->field_whatever['und'][0]['value'] = "bobs your uncle";
// The exact structure of this is different depending on the field type
// I suggest you create a node manually and then use devel to see its
// structure then reproduce it here.
// Note your field collection stuff does NOT get saved at this point.
// Save your node.
if ($node = node_submit($node)) {
node_save($node);
} else {
print '<h1>OMG IT BROKE!!!!</h1>';
}
// Just to be safe.
$node = node_load($node->nid);
// At this point you probably have an array of data as your field
// collection stuff. loop through it to create your collections
foreach($array_of_data as $key => $value){
$field_collection = array(
'field_name' => 'field_name_of_your_field_collection_field',
);
// Add your fields here like:
$field_collection['field_whatever']['und'][0]['value'] = $value['in your face'];
// Again manually create a node and see the structure from devel.
$entity = entity_create('field_collection_item', $field_collection);
$entity->setHostEntity('node', $node);
$entity->save();
}
@chadmandoo
Copy link

Thanks just saved me a few hours of discovery!

only difference is you can easily create the node programmatically:

$node = entity_create('node', array('type' => 'requisition_form'));
$node_wrapper = entity_metadata_wrapper('node',$node);
$node->title->set("My Title");
$node->field_whatever->set("Whatever");
$node->field_whatever_multiple->set(array("what", "ever"));
$node_wrapper->save();
$node = node_load($node_wrapper->getIdentifier());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment