Skip to content

Instantly share code, notes, and snippets.

@oxyc
Created April 24, 2012 15:45
Show Gist options
  • Select an option

  • Save oxyc/2480870 to your computer and use it in GitHub Desktop.

Select an option

Save oxyc/2480870 to your computer and use it in GitHub Desktop.
<?php
/**
* Implements hook_entity_insert().
*
* We use this hook as it's called later than node_insert().
*/
function HOOK_entity_insert($node, $type) {
module_field_collection_stuff($node, $type);
}
/**
* Implements hook_entity_update().
*/
function HOOK_entity_update($node, $type) {
module_field_collection_stuff($node, $type);
}
/**
* Do your magic
*/
function module_field_collection_stuff($node, $type) {
if ($type != 'node' || $node->type != 'my_content_type') {
return;
}
// Create a dummy node so we can update the real node without
// triggering all the node fields hooks.
$update = new stdClass();
$update->nid = $node->nid;
$update->type = $node->type;
$update->status = $node->status;
$update->language = $node->language;
$values['field_name'] = 'field_collection_field';
$values['field_item_first'][LANGUAGE_NONE][0]['value'] = 'value';
$values['field_item_second'][LANGUAGE_NONE][0]['value'] = 'second';
// Create new field collection item.
$field_collection_item = entity_create('field_collection_item', $values);
// Attach it to the node
$field_collection_item->setHostEntity('node', $update, LANGUAGE_NONE, true);
// Save field-collection item, without trigger the nodes own save.
// This is because you might want to insert multiple field collection items.
$field_collection_item->save(TRUE);
// Update the fields.
field_attach_presave('node', $update);
field_attach_update('node', $update);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment