Created
August 27, 2013 18:33
-
-
Save bassettsj/6357255 to your computer and use it in GitHub Desktop.
Don't use this script for a module!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Returns field values as actual entities where possible, | |
* also allows selection of individual items to be returned. | |
* Code from http://drupal7ish.blogspot.com/2011/03/getting-field-data-out-of-entities.html | |
* Modified to handle field collections, but the case where a field collection has multiple fields is not yet handled. | |
*/ | |
function field_fetch_value_fetch($entity_type, $entity, $field_name, $get_delta = NULL, $get_key = NULL) { | |
$values = array(); | |
if (isset($entity->$field_name) && !empty($entity->$field_name)) { | |
if ($entity_type == 'field_collection') { | |
if (!is_a($entity, 'FieldCollectionItemEntity')) { | |
$entity = field_collection_item_load($entity); | |
} | |
$items = $entity->{$field_name}['und']; | |
} else { | |
$items = field_get_items($entity_type, $entity, $field_name); | |
} | |
if (!is_array($items)) { | |
watchdog('Field Fetch Value', '$items is not an array: @items', array('@items' => print_r($items)), 'WATCHDOG_NOTICE'); | |
return NULL; | |
} | |
foreach ($items as $delta => $item) { | |
$value = $item; | |
$keys = array_keys($item); | |
if (count($keys)==1) { | |
$key = $keys[0]; | |
switch ($key) { | |
case 'nid': | |
$value = array_shift(entity_load('node', array($item[$key]))); | |
break; | |
case 'uid': | |
$value = array_shift(entity_load('user', array($item[$key]))); | |
break; | |
case 'tid': | |
$value = array_shift(entity_load('taxonomy_term', array($item[$key]))); | |
break; | |
case 'vid': | |
$value = array_shift(entity_load('taxonomy_vocabulary', array($item[$key]))); | |
break; | |
case 'value': | |
$value = $item['value']; | |
break; | |
} | |
} | |
else { | |
if ($get_key && isset($item[$get_key])) { | |
$value = $item[$get_key]; | |
} | |
elseif (array_key_exists('value', $item)) { | |
$value = isset($item['safe_value']) ? $item['safe_value'] : $item['value']; | |
} | |
} | |
$values[$delta] = $value; | |
} | |
} | |
if (is_numeric($get_delta)) { | |
return isset($values[$get_delta]) ? $values[$get_delta] : NULL; | |
} | |
return $values; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
used in places like this