Using entity metadata wrappers with Drupal

September 15
blog author


Drupal Developer

Entity metadata wrappers are PHP wrapper classes used in order to simplify the code dealing with entities(nodes, taxonomy...). They abstract structure so that a developer can write code in a generic way when accessing entities and their properties.

The Entity API in Drupal 7 provides a set of common functions and classes to make it easier for developers to create their own custom entity types or to work with other already existing ones in a generic way.

Everybody already used this kind of code which is sometimes a pain.

//Code sample

$my_field = $node->field_custom_field[LANGUAGE_NONE][0]['value'];

We have two problems with this kind of code, first, the langage is hard coded into the field value lookup and we'll see PHP warnings if the field has no data.

How wrappers make life easier

The wrapping classes are provided by the Entity API module. 

The magic of wrappers is in their use of the following three classes:

  • EntityStructureWrapper
  • EntityListWrapper
  • EntityValueWrapper

Here is an example of using wrappers with nodes

// Code sample

$wrapper = entity_metadata_wrapper('node', $node);


This will print the list of all known fields on the node and their properties can be accessed easily. The wrapper object is defined so now let's check the synthax for querying values of fields.

The code sample on the "Introduction" was the old approach for querying fields, here is the Entity metadata wrapper approach

// Code sample

$number_of_articles = $wrapper->field_number_of_articles->raw();

 raw() retrieves the raw value from the field field_number_of_articles. It is useful for integer fields...

Using wrapper with a single select taxonomy

// Code sample (exract specific level)

$level = $show->field_level;

$tid = $level[LANGUAGE_NONE][0]['tid];

$term = taxonomy_term_load($tid);

$variables['level'] = $term->name;

This was the old approach. Here is the sample code using wrappers.

$variables['level'] = $wrapper->field_level->value()->name;

As we said with the old approch we had to specify the language to retrieve the field value but Entity Mmetadata wrappers has native support for accessing the value of langage specific fields.

// Code sample with wrappers

global $language;

// get Localised custom_field

$my_custom_field = $wrapper->language($language->language)->custom_field->raw(); 

Advantages of using entity metadata wrappers

  • The code is more readable
  • Stop hardcoding the language key into the array lookups
  • Prevent PHP for giving warnings when trying to access properties that does not exist

This article was an overview of the wrappers on drupal 7.