Drupal - What's best practice when working with the language[und]?

I find that using the Entity API module is a great help and also makes code more readable. The above code will not always work, since the language of the node and the language of the field can be different.

With the entity API module, and its wrapper, you can use the following code:

 $node_wrapper = entity_metadata_wrapper('node', $node);
 $field_val = $node_wrapper->field_test->value();

This should be bullet proof. One thing about using the entity module is that if you try to access a field that doesn't exist, you will get a nasty error and an exception thrown instead of a notice and wrong behavior.

To avoid this, you could do try/catch like this

try {
  $field_val = $node_wrapper->field_doesnt_exist->value();
} catch (EntityMetadataWrapperException $e) {
  $field_val = 'default/fallback value';
}

Or you can use isset() which EntityMetadataWrapper handles internally:

$field_val = 'default/fallback value';
if (isset($node_wrapper->field_doesnt_exist)) {
  $field_val = $node_wrapper->field_doesnt_exist->value();
}

For reading, you should always be able to use field_get_items(), which will pick the correct language for you and also check if the field has any values.

Unfortunately, the field API is very limited in 7.x, there is no way to get e.g. the first field item, don't even dare to ask about getting the value with a single function call... And there is no field_set_items() counterpart.

So yes, entity API module does provide a nicer API with the drawback that it also comes with quite a bit of overhead (It basically converts every single value to wrapper objects which have tons of nested property info arrays attached to them). Trying to dump an entity wrapper will usually get you either nothing or a wall of unreadable arrays.

Tags:

Entities