Thursday, April 21, 2016

Drupal - Field Collection - Appending/Inserting an Entity

Kudos for this solution goes to Drupaler Justin Fraser :
Slightly changed description to fit more of my append/insert issue.


I had an issue where I was trying to append new field collection entity to the 'user' Field Collection and doing so would delete any existing items. The solution was to directly load the user entity and not depend on the global $user as that one doesn't have the field collection information.
$thisUser = entity_load('user', array($user->uid));
$thisUser = $thisUser[$user->uid]; //make thisUser the user object, not an array of user objects

$newFieldCollectionItem = array();
$newFieldCollectionItem['field_name'] = 'field_download';
$newFieldCollectionItem['field_download_filename'][LANGUAGE_NONE][0]['value'] = $src;
$newFieldCollectionItem['field_download_date'][LANGUAGE_NONE][0]['value'] = time();

$newFieldCollection = entity_create('field_collection_item', $newFieldCollectionItem);
$newFieldCollection->setHostEntity('user', $thisUser);
$newFieldCollection->save();

Line 2 $thisUser[$user->uid] is what made it work for me.

The rest of the code had been the exact same, but adding line 2 is what did it for me!!!