There are two great ways I’ve found to quickly access an entity’s field values in a Drupal-friendly way.
Both of these approaches assume that you know the type of entity you’re working with and that you already have your entity loaded into a variable available to you. This week I’ll be focusing on the handy Drupal API function field_get_items() and next week I’ll take a look at how to use Entity Metadata Wrappers to get the job done.
field_get_items()
If you need to access the array of items held in a field attached to your entity, you can easily accomplish that with field_get_items(). Here’s a code example showing how to use it:
// Grab the items in this field
$field_items = field_get_items('my_entity_type', $my_entity, 'field_my_field_name');
// Iterate over each item in the field
foreach ($field_items as $field_item) {
// Do what you'd like with the data contained in each $field_item here
}
If you want just the first item in your entity’s field, the following code example might be helpful:
// Grab the items in this field
$field_items = field_get_items('my_entity_type', $my_entity, 'field_my_field_name');
// Extract just the first item
$first_item = current($field_items);
// Using the $first_item in your field, get something done!
More information on how to use field_get_items() can be found on the Drupal API page for field_get_items().