Skip to content

Instantly share code, notes, and snippets.

@bassettsj
Created August 27, 2013 18:33
Show Gist options
  • Save bassettsj/6357255 to your computer and use it in GitHub Desktop.
Save bassettsj/6357255 to your computer and use it in GitHub Desktop.
Don't use this script for a module!
<?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;
}
@bassettsj
Copy link
Author

used in places like this

function _get_image_with_style($vars, $field_name, $style_name, $entity){
  // Use the existing image values for uri and alt, but set image style as directed
  $uri   = field_fetch_value_fetch($entity, $vars['element']['#object'], $field_name, 0, 'uri');
  $alt   = field_fetch_value_fetch($entity, $vars['element']['#object'], $field_name, 0, 'alt');
  $title = field_fetch_value_fetch($entity, $vars['element']['#object'], $field_name, 0, 'title');
  $options = array(
    'style_name' => $style_name,
    'path'       => $uri,
    'alt'        => $alt,
    'title'      => $title,
  );
  // Return the HTML for the properly styled image
  return theme_image_style($options);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment