5

So I want to get some field values that I need as input, sometimes for rendering. According to this page:

http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

It is a mistake to hard-code 'und' for internationalization, so to avoid this the author says that we should use field_view_field().

I personally, don't need all info related to the field, just the value. So I opt for field_get_items() and then field_view_value() as outlined in the blog post. But this seems a lot of work just to get a single value of a field (plus we have to find and load the node). Do we really have to do so many steps to get a simple field value? I would have thought that this would be a very common function that users need.

I'm wondering that, barring any simple method, I could just grab the value directly from field_get_items()[0]['value']. Maybe the drawbacks are that it doesn't pass through any sanitation routines? You can see more info here (trying to grab 'axis1t'):

enter image description here

Just looking for possible alternatives because my code is becoming somewhat bloated to keep getting field values this way along with the fact that they are burried inside field_collections.

1
  • I've always wondered the same thing. There must be a better way?
    – Chris
    Mar 24, 2015 at 1:55

1 Answer 1

3

If you are worried about bloat, just write your own field processor and keep it all on the level. That way you are using safe values, your site won't trip over if the language settings wiggle about and you can reuse your code in your next site.

You would call it wherever you like and because you know what you're expecting to get back, you could work with it immediately.

Something like:

<?php 
/* get the values out of a field */
function magic_field_values($node, $field_name, $delta = null){
  $field_items = field_get_items('node', $node, $field_name);
  /* if a delta value is supplied, render that item otherwise, send the lot
  back. */ 
  if ($delta){
    return field_view_value('node', $node, $field_name, $field_items[$delta]);
  } else
  return $field_items;
}
?>

Then call it with:

<?php 
$cheese_samples = magic_field_values($node, 'field_cheese_samples');
foreach $cheese_samples as $sample {
//do stuff
}
?>
1
  • ...$field_items[$delta]
    – commonpike
    Aug 13, 2015 at 23:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.