Nov 18th, 2012
How to use Entity Metadata Wrapper.
also see entity_get_property_info(), entity_view(), entity_create(), entity_delete(), and entity_save()
entity_metadata_wrapper()
Lets you access the entity properties and fields directly.
See: http://drupal.org/node/1021556
Examples:
<?php $wrapper = entity_metadata_wrapper('node', $nid); // Uncomment the line below to see all the available properties, requires the Devel module. // dpm($wrapper->getPropertyInfo()); $sanitized_title = $wrapper->title->value(array('sanitize' => TRUE)); // you don't need to worry about what language the entity is stored as $raw_text = $wrapper->field_text->value(); $mail = $wrapper->author->mail->value(); $wrapper->language('en')->field_text->value(); // however, if you want to get a translation, you can $terms = $wrapper->field_tags->value(); $wrapper->field_tags[] = $term; $options = $wrapper->field_tags->optionsList(); $label = $wrapper->field_tags[0]->label(); $access = $wrapper->field_tags->access('edit'); $wrapper->author->mail->set('loopduplicate@example.com'); $wrapper->save(); // necessary after setting values ?>
<?php // Unpublishes a node. $wrapper = entity_metadata_wrapper('node', $nid); $wrapper->status->set(0); $wrapper->save(); ?>
From the README:
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, e.g. $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: $wrapper->body->value->raw();
More info on creating your own entities at:
http://denver2012.drupal.org/program/sessions/drupalize-your-data-use-entities
One thing that is nice about just using nodes instead of creating your own entity is nodes have revision support.