spot_imgspot_img

Accessing Field Values in Drupal 7

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 already have your entity loaded into a variable available to you. This week, I’ll be focusing on Entity metadata wrappers.

Entity metadata wrappers

Entity metadata wrappers are another great way to get at field data. And, with entity metadata wrappers, you can quickly set field values too.

Here’s a simple example of how to utilize an entity metadata wrapper to read field data:


// Wrap our entity
$my_entity_type_wrapper = entity_metadata_wrapper('my_entity_type', $my_entity);
// Grab the value
$value = $my_entity_type_wrapper->field_my_field_name->value();

And here’s an example of how to set a field’s value:


// Wrap our entity
$my_entity_type_wrapper = entity_metadata_wrapper('my_entity_type', $my_entity);
// Set the value
$my_entity_type_wrapper->field_my_field_name->set('Example data');

And that’s it (pretty simple)! More information and examples can be found on the Community Documentation page for entity metadata wrappers.

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