Last updated April 15, 2014. Created by fago on January 10, 2011.
Edited by massiws, elmertoft, danielphenry, a.milkovsky. Log in to edit this page.

The Entity API provides wrapper classes you may use to make dealing with the values of an entity's properties and fields easier. Wrappers make it easier to get and set the values of fields and properties as well as to programmatically retrieve additional information about these elements and iterate over lists of values in a consistent manner.

For example consider the following method of accessing the value of a field attached to a node. This is a pattern that we see used often when working with entities in Drupal. However there are a couple of things that make this less than ideal. For example what if the user had requested the page in a different language? Or what about the case where the ['value'] key just doesn't exist like with image and file fields?


Using metadata wrappers from the entity module we can access this information like so:


How about an example of making things consistent? All Drupal entities have a label of some sort. A string that can be treated as the canonical human readable name of an entity. Nodes all have a title property and user accounts all have a name property. Given a standard Drupal entity it can be hard to know which property should be treated as the label. Metadata wrappers provide us with a consistent way of getting at this kind of information for any entity.

// Unified way of getting $node->title, $user->name, ...
// Unified way of getting $node->nid, $user->uid, ...
// Unified way of getting $node->type, ...

Examples taken from the README

For making use of this information (metadata) the module provides some
wrapper classes which ease getting and setting values. The wrapper supports
chained usage for retrieving wrappers of entity properties, e.g. to get a
node author's mail address one could use:
  $wrapper = entity_metadata_wrapper('node', $node);
To update the user's mail address one could use
  $wrapper->author->mail = '';
The wrappers always return the data as described in the property
information, which may be retrieved directly via entity_get_property_info()
or from the wrapper:
  $mail_info = $wrapper->author->mail->info();
In order to force getting a textual value sanitized for output one can use,
  $wrapper->title->value(array('sanitize' => TRUE));
to get the sanitized node title. When a property is already returned
sanitized by default, like the node body, one possibly wants to get the
not-sanitized data as it would appear in a browser for other use-cases.
To do so one can enable the 'decode' option, which ensures for any sanitized
data the tags are stripped and HTML entities are decoded before the property
is returned:
  $wrapper->body->value->value(array('decode' => TRUE));
That way one always gets the data as shown to the user. However if you
really want to get the raw, unprocessed value, even for sanitized textual
data, you can do so via:

Many more examples can be found in the tests.

Working with lists

A list value that contains wrappers, such as a multi-valued reference field, can be iterated over thus:

= entity_metadata_wrapper('node', $node);
  foreach (
$wrapper->field_taxonomy_terms->getIterator() as $delta => $term_wrapper) {
// $term_wrapper may now be accessed as a taxonomy term wrapper.
$label = $term_wrapper->label->value();

Adding values to a list value, such as a multi-valued entity reference field, can be accomplished like this:

= node_load($nid);
$w_containing_node = entity_metadata_wrapper('node', $containing_node);
$new_ref = node_load($ref_nid);
$curr_list = $w_containing_node->field_entity_reference_field->value();
  if (!
$currList = array();
$curr_list[] = $new_ref;

Deleting values

To delete values, there is no ->delete() method on the fields. You have to use this way to correctly delete a value:

// Using an empty ->set(NULL) removes the value - without NULL you'll get a PHP notice that set($value) requires 1 parameter.
// And handles correctly the deltas when using multiple values fields

Introspecting wrappers

To get a list of all available properties of a(n) (entity)wrapper, you can use the following snippet (requires the devel module to be installed and enabled):


Example of using value(), set() and save()

= entity_metadata_wrapper('node', $node);
$var = $node_wrapper->field_number->value() + 1;

Get first value of multifield (multiple-value field)

Just set value index directly after field name:

= $wrapper->field_tags[0]->name->value();

Example using field collections

// Populate the fields.
$ewrapper = entity_metadata_wrapper('node', $node);
// Create the collection entity and set it's "host".
$collection = entity_create('field_collection_item', array('field_name' => 'field_facilities_requested'));
$collection->setHostEntity('node', $node); 
// Now define the collection parameters.
$cwrapper = entity_metadata_wrapper('field_collection_item', $collection);
// Save.


It's recommended to wrap code in try...catch section when you work with entity_metadata_wrapper() to catch EntityMetadataWrapperException.
You can add hints for you in watchdog for debugging errors. For example function name or line number. Example:

try {
$node_wrapper = entity_metadata_wrapper('node', $node);
$price = $node_wrapper->field_product->field_price->value();
catch (
EntityMetadataWrapperException $exc) {
'See '  . __FUNCTION__ . '() ' $exc->getTraceAsString(),

Get Start-date and End-date values from Date fields

If you have Date fields (provided by Date module) you can get Start/End values from a field in this way:

= entity_metadata_wrapper('node', $node);
$start_date = $wrap_node->field_my_data->value()['value'];
$end_date = $wrap_node->field_my_data->value()['value2'];

or alternatively:
= entity_metadata_wrapper('node', $node);
$start_date = $wrap_node->field_my_data->value->value();
$end_date = $wrap_node->field_my_data->value2->value();

Looking for support? Visit the forums, or join #drupal-support in IRC.


I would love to see an example of saving a list of nodes (list).

Is it something like this?

= entity_metadata_wrapper('myEntity', $myEntity);
$node1 = new StdClass;
$node1->title = 'Node 1';
// ...
$node2 = new StdClass;
$node2->title = 'Node 2';
// ...
$wrapper->myProperty->value(array($node1, $node2));

Here's a list of example uses from entity.test

$wrapper->author = 0;
$wrapper->url = 'dummy';
$wrapper->author->mail = 'foo';
$wrapper->author = NULL;
$wrapper->body->set(array('value' => "<b>The second body.</b>"));
$wrapper->body->set(array('value' => "<b>Der zweite Text.</b>"));
$wrapper->author = $user->uid;
$wrapper->{$property}[0] = '2009-10-05';
$wrapper->field_image = array('fid' => $file->fid);
$wrapper->parent[] = $term_parent2;
$wrapper->field_tags[1] = $term_parent;
$wrapper->field_tags = NULL;
$wrapper->field_text[0] = 'the text';
$wrapper->field_text[0]->set(array('value' => "<b>The second body.</b>"));
$wrapper->field_text2->summary = 'the summary';
$wrapper->field_text2->value = 'the text';
$wrapper->field_file[0] = array('fid' => $file->fid, 'display' => FALSE);
$wrapper->field_file[0]->description = 'foo';
$wrapper->field_file[0]->display = TRUE;
$wrapper->field_file[1]->file = $file;
$wrapper->field_file[] = array('description' => 'test');
$wrapper->field_file = NULL;
$wrapper->field_image = array('fid' => $file->fid);
$wrapper->field_image->alt = 'foo';
$wrapper->field_image->file = $file;
$wrapper->field_image = array();

^^ Generated via:
# grep "^\W*\$wrapper->" entity/entity.test | tr -s " "

Can i ask how to create a new node with 'entity_metadata_wrapper' or other function? thx :)

If you need to use the wrapper on taxonomy terms you should use:

$wrapper = entity_metadata_wrapper('taxonomy_term', $term);

I couldn't find a list of valid values for the $type property.

Look for hook_entity_info() implementations to find out the name.

For example, about the taxonomy module, this command shows the entity type:

$ cat taxonomy.module | awk '/function taxonomy_entity_info()/{getline; getline; print}'
   'taxonomy_term' => array(

Since the type is always two lines after the function declaration, getline is used twice.

Using this way, you can see all the entity types availables in core with the right regex:

$ cd modules/
$ find . -name '*.module' -print | xargs cat | awk '/_entity_info\(\) {$/ {getline; getline; print}'
    'user' => array(
    'comment' => array(
    'node' => array(
    'file' => array(
    'entity_cache_test' => array(
    'taxonomy_term' => array(

Now, what's entity_cache_test? I have no idea :-)


just a small suggestion : I have observed that value() is supported only in case of simple properties like integer, text etc.. But if u have Taxonomy or Node Reference or User Entity Reference field and typically if u want to compare IDs then you can use raw(). Use label() if u want readable code than using IDs..

I used it like this :

$thenode = entity_metadata_wrapper('user', 3);
if ( $thenode->field_rank->label() == 'Active Distributor')
    {/*lights camera action..*/}

**Lot of useful functions available in

Ananya MultiTech Private Limited.


Does somebody have more documentation about how to work with taxonomies? I use several term reference fields in the user profile / account settings. Some allow multiple values. I am trying to programmatically adjust these terms. I use the wrapper to load the user entity:
$data = entity_metadata_wrapper('user', $user);

If it is a single-value field, I assume
$data->field_term_reference_field = 23;
would overwrite any existing tag with the tid 23.

How does it work if is is a multi-value field?

Can I just add multiple tags like this?
$data->field_term_reference_field = 23;
$data->field_term_reference_field = 43;
$data->field_term_reference_field = 51;

Is there a way to clear all terms in a given vocabulary for the given user, e.g. get rid of all existing tags and set a new one like this:
$data->field_term_reference_field = 23;
Or do I have to iterate through all tags for the user and clear the all individually?


I just figured out:

$tag contains the tid.

= entity_metadata_wrapper('node', $entity);
foreach (
$random_tags as $i => $tag) {
$wrapper->field_tags[$i] = $tag;

Just a general question about using entity metadata wrappers with ajax:

When setting and saving fields of an entity through the entity metadata wrapper, does the value get updated between ajax calls or is it being done when the entire page gets reloaded?

The reason I'm asking is that I have a situation where if I set the values of fields directly on the entity it's being stored between my calls. If I do it via the wrapper ( $wrapper->field->set('value'); $wrapper->save(); ) it reverts back to the original value.

Am I posing a relevant question or am I doing something wrong in my code?


Seems like there is a mistake in the README concerning getting raw values. E.g. for field_test it actually should be $wrapper->field_test->raw() instead of $wrapper->field_test->value->raw().

The text above suggests dpm($wrapper->getPropertyInfo()); to inspect the properties of the wrapped objects, but all that gives you is metadata about the properties. It doesn't, for example, give you any of the property values.

In the hopes this helps someone else, I wrote my own helper to debug wrapped objects:

function _wrapper_debug($w) {
  $values = array();
  foreach ($w->getPropertyInfo() as $key => $val) {
    $values[$key] = $w->$key->value();
  return $values;

That was very helpful. Thanks!

Trevor Twining
Senior Consultant, CGI


How do you theme a entity_metadata_wrapper?

For example, I have a field that is of integer with the comma specified as the separator. However when I do this:

     $row_data = entity_metadata_wrapper('field_collection_item', $row);
     dsm($row_data->field_test_base->value());      // This prints just the integer
      dsm(field_view_field('field_collection_item', $row, 'field_test_base'));     // This causes an error

I assumed that field_view_field would be the function I wanted but I can't get that to work. I can of course add the commas and $ dollar signs manually, but that seems wasteful if I've set the field prefix to be a dollar sign and the field integer separator to be a comma. Adding the comma and prefix are tasks taken care of by the theme engine so I imagine I should be able to feed the wrapper back to either a theme function or the render function.

Any suggestions or help is much appreciated.


This took me a while to figure out. Adding an image works like this:

= [some way of getting a file object, e.g. system_retrieve_file() or file_load()];
$wrapper->[your field name goes here]->file->set($image_file);

this worked for adding existing images:

$fc_wrapper->field_step_image->set(array('fid' => 49031));

Nate Andersen
Lead Drupal Developer at American Media Inc.

I didn't see it on this page. You can load the vocab like so:

entity_metadata_wrapper('taxonomy_vocabulary', $vid);

Where $vid is an integer.

Note: A dump of ->raw() or ->value() shows that it has no path to the terms within. This would only be if you need some base information about the vocab.

How to remove reference from filefield? Tried different ways without success.