Example: Programmatically adding field collection entries to a node
Last updated on
30 April 2025
You are browsing documentation for an older version of Drupal, which is not supported any longer, and the information may not be correct. See current documentation for Contributed modules
In this example a function adds an entry to a node with a field collection named field_activity_log.
function foo_log_activity($node, $message, $uid = NULL) {
// Load the controller class file.
module_load_include('inc', 'entity', 'includes/entity.controller');
// Use the currently logged in user if a $uid argument is not defined.
global $user;
if (empty($uid)) {
$uid = $user->uid;
}
// Grab the current time in the format required by our date field. We need
// gmdate() here to get a time in UTC which is how everything is stored
// internally.
$now = gmdate('Y-m-d H:i:s');
// Setup the values in the structure expected by the field_collection entity.
$values = array(
'field_name' => 'field_activity_log',
'field_activity_log_date' => array(
LANGUAGE_NONE => array(array('value' => $now)),
),
'field_activity_log_message' => array(
LANGUAGE_NONE => array(array('value' => $message)),
),
'field_activity_log_user' => array(
LANGUAGE_NONE => array(array('uid' => $uid)),
),
);
$entity = entity_create('field_collection_item', $values);
// Attach the field_collection entity to the application node. This has to
// happen separately so that it actually works -- you can't just specify
// this via the $values array.
$entity->setHostEntity('node', $node);
// Save the entity. Since it's attached to the right application node, this
// will both create the field_collection entity and update the application
// node to point to the new field_activity_log record.
$entity->save();
}
Help improve this page
Page status: Not set
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion