7

What is the correct way to render a Drupal 7 image field and show the default image if the field is empty?

If I use field_get_items it will simply return FALSE when the field is empty.

migrated from stackoverflow.com Jun 3 '12 at 23:52

This question came from our site for professional and enthusiast programmers.

15

I think best practice would probably be to use field_view_field():

$view = field_view_field('node', $node, 'field_image');
print render($view);

That will render the field as if it was attached to an entity view, and as such will provide the default image if none is available.

  • 2
    As documented, you can either use the display settings from an existing view mode or provide your own as fourth argument. Also, if you only want the field value with its label and wrapper markup, use field_view_value(). – Pierre Buyle Jun 3 '12 at 16:48
10

You can also image style (image cache presets in D6) like this:

render(field_view_field('user', $user, 'field_avatar', array('settings' => array('image_style' => 'avatar'))));
  • render() requires a variable passed as reference, and since field_view_field() doesn't return a reference, that code raises an error. See Clive's answer to see how render() should be called. – kiamlaluno Aug 14 '13 at 15:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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