Skip to main content

The One and Only entity_metadata_wrapper!

May 27 '16

entity metadata wrapper

How many times have you been in a preprocess function or a custom module trying to get the value, or editing an entity? If you’ve had the pleasure to work with Drupal code before, my guess is plenty!

This is a very common process for things like checking against a custom field value to determine layout, send information to a third party API (i.e. client CRM, or analytics tracking) or, like we do here at TAG, include content changes in a release script.

As flexible and powerful as this process can be, dealing with the endless arrays that Drupal provides is tedious and unreliable. Lets look at this snippet of code for example:

$body = $node->body[LANGUAGE_NONE][0][‘value’];

 

The obvious problem here with getting the value of a node’s body field is the language handling. If at any point the entity gets translated, the code will have to be updated. I also personally think that it’s not very clean.

Thankfully, entity_metadata_wrapper is here to rescue us. This is a entity_api function, so that module will have to be installed and enabled. In your code you can then do the following:

$node = entity_metadata_wrapper(‘node’, $nid); // The first argument is the entity type. The second is the entity ID or the entity object if it’s already loaded.
$body = $node->body->value(); // The body of the node in a much cleaner and maintainable way.

 

You can also easily set values like this:

$node->body->value =New body value’;

 

Or even better, by using the setter method:

$node->body->set(New body value’);

 

Don’t forget to save by using the new save method:

$node->save();

 

Dealing with a field with multiple values like a list? No problem! Just try this:

foreach ($node->field_list->getIterator() as $delta => $list_item) {
    $label = $list_item->value();
}

 

Dealing with entity references? No problem! The referenced entity is "wrapped" as well, and can be treated the same way. Check out this example with a node reference field:

$referenced_nid = $node->node_reference->raw(); // This returns the id of the referenced entity.
$referenced_node = $node->node_reference->value(); // This returns the referenced entity object.
$referenced_title = $reference_node->title(); // The referenced entity’s title.

 

Overall, you can see how this way of dealing with Drupal entities is much more elegant and effective. It personally saves me a lot of time and the grief of having to look at endless arrays and dealing with undefined index errors.

There is much more to this that can be found on the drupal.org documentation page here.

As always, don’t hesitate to correct me or ask questions in the comments section. I look forward to hearing your thoughts on the matter!

 

Read more about: