spot_imgspot_img

Accessing Field Values in Drupal 7 Using field_get_items()

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().

Get in Touch

spot_imgspot_img
spot_img

Get in Touch

[td_block_social_counter facebook="tagdiv" style="style6 td-social-boxed" open_in_new_window="y" f_counters_font_family="394" f_network_font_family="891" f_counters_font_size="eyJhbGwiOiIxNCIsImxhbmRzY2FwZSI6IjEzIiwicG9ydHJhaXQiOiIxMiJ9" f_network_font_size="eyJhbGwiOiIxMyIsImxhbmRzY2FwZSI6IjExIiwicG9ydHJhaXQiOiI5In0=" counter_color="#ffffff" counter_color_h="#ffffff" network_color="#ffffff" network_color_h="#ffffff" tdc_css="eyJsYW5kc2NhcGUiOnsibWFyZ2luLWJvdHRvbSI6IjMwIiwiZGlzcGxheSI6IiJ9LCJsYW5kc2NhcGVfbWF4X3dpZHRoIjoxMTQwLCJsYW5kc2NhcGVfbWluX3dpZHRoIjoxMDE5LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMjAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3NjgsInBob25lIjp7Im1hcmdpbi1ib3R0b20iOiI0MCIsImRpc3BsYXkiOiIifSwicGhvbmVfbWF4X3dpZHRoIjo3NjcsImFsbCI6eyJtYXJnaW4tYm90dG9tIjoiNDAiLCJkaXNwbGF5IjoiIn19" twitter="tagdivofficial" youtube="tagdiv"]

Latest Posts