Field collections : CRUD(Create/Update/Delete) operations programmatically
With the entity system in Drupal 7 the fields has a real big value and what about a field which has number of fields tha we can manage inside it? Isn't that amazing? Drupal entity system allows to create collection of fields as entity and make it work like a field. Wow!. Field Collection module is the successor of that idea. Recently, I've been working on a drush script which clone nodes and update it's fields so programmatically update on the fields was required.
Create:
$field_collection_item = entity_create('field_collection_item', array('field_name' =>'field_text')); // Create new field collection item.
$field_collection_item->setHostEntity('node', $node); // This is required, there should be a host entity, this case I used a node.
$field_collection_item->field_text[LANGUAGE_NONE][0]['value'] = 'Test Value';
$field_collection_item->save(); // Save the field collection item.
Update:
$field_collection_item = field_collection_item_load($item_id); // Load that field collection item.
$field_collection_item->field_text[LANGUAGE_NONE][0]['safe_value'] = 'New value'
$field_collection_item->save(); // Save field-collection item.
Delete:
entity_delete_multiple('field_collection_item', array($item_id)); // Delete field collection item.
© Heshan Wanigasooriya.RSS🍪 This site does not track you.