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.
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI 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.
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.