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.
It appears that field_get_items()
will always return FALSE if used in hook_field_collection_presave()
when saving a new field collection item. It does work on subsequent saves. It does not work in hook_entity_presave()
either.
To test, save a new host node with a non-empty field collection item and check the output of this.
function MYMODULE_field_collection_item_presave(FieldCollectionItemEntity $field_collection_item) {
if ($field_collection_item->field_name == MY_FIELD_COLLECTION_NAME) {
print '<pre>' . __FUNCTION__ . PHP_EOL;
// field_get_items() does not work here.
print_r(field_get_items('field_collection_item', $field_collection_item, MY_COLLECTION_FIELD_NAME));
}
}
function MYMODULE_entity_presave($entity, $type) {
print __FUNCTION__ . "($type)" . PHP_EOL;
if ($type == 'field_collection_item' && $entity->field_name == MY_FIELD_COLLECTION_NAME) {
// field_get_items() does not work here.
print_r(field_get_items('field_collection_item', $entity, MY_COLLECTION_FIELD_NAME));
}
elseif ($type == 'node' && $entity->type == MY_NODE_TYPE) {
// but field_get_items() works here for nodes.
print_r(field_get_items('node', $entity, MY_NODE_FIELD_NAME));
print '</pre>';
die;
}
}
field_get_items()
only works on first save for the node, not for the field collection. Preliminary digging suggests this is because field_language()
fails to return a language code for the field.