My last blog post demonstrated the ability to retrieve and set values using the Entity Metadata Wrapper. Today, I’m going to follow that up by showing how to create and set values for field collections as well as taxonomy terms.

Field Collections:

Creating a field collection on the fly is done by using the “entity_create” function available from the entity module. Once the entity field collection object is created, associating that object to the node is done by using the "setHostEntity" function and passing the node you wish to associate to.
$new_node = node_load($new_node_id, NULL, TRUE);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_flights_simple_trips'));
$field_collection_item->setHostEntity('node', $new_node);
$field_collection_item->field_cc_transpo_main_simple[LANGUAGE_NONE][]['nid'] = $new_node_id;
$field_collection_item->save();
Saving field collection data is done by grabbing the ID that is stored within the field value. However, calling "entity_metadata_wrapper" with the first parameter of "field_collection_item", will retrieve the entire field collection allowing you to manipulate it. In the example below, I set the phone number type (cell, office etc) and save the field collection.
$raw_collection = $node_data->field_phone_number->value();
$field_collection = entity_metadata_wrapper('field_collection_item', $raw_collection);
$field_collection->phone_number_type->set($new_value);
$field_collection->save();

Taxonomy:

The way to create taxonomy terms using Entity API is very similar in creating field collections. The only code that changes is the parameter you pass into the "entity_create" function.
$field_collection_item = entity_create('taxonomy_term', array('field_name' => 'field_tags'));
$field_collection_item->setHostEntity('node', $node);
$field_collection_item->save();
The old approach to retrieving a taxonomy term would involve loading up the taxonomy term by tid. However, with entity metadata wrapper, you can use the wrapper to set / get taxonomy term values much easier.
$wrapper = entity_metadata_wrapper('taxonomy_term', $tid);
$term = $wrapper->value();
$wrapper->value = "New Value";
$wrapper->save();
These examples show how using the Entity API module and the methods it provides can make CRUD for entities much, much easier and less prone to errors and bugs. In case you missed it, read Part 1 here.
Read Next
Appnovation Blog Default Header

Fixed vs Estimated: Understanding the Methodology Triangles

08 March, 2013|12 min