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.