Cleanest/simplest method to render image fields with Drupal 7
September 26, 2011 - 6:40pm — brad
A common issue when building a site in Drupal: you've got a $node, $vars['node'], or $form_state['node'] and need to render an image (with image style) from one of the fields. I am building a custom form in this instance, and need to show the first image stored in some loaded nodes.
// Get the node loaded via node_load into $node. // Use field_get_items to get the correct field data. // Use current() to get the first item in the returned array. $field_picture = current(field_get_items('node', $node, 'field_picture')); // Reuse the field data since it already contains 'alt' and 'title'. // Add style_name and path. $field_picture['style_name'] = 'image_style'; $field_picture['path'] = $field_picture['uri']; // Render the image to HTML using the field data. $picture = theme('image_style', $field_picture);
If you are going to be using the above code often, you should probably put in an function in a custom site module.
Add new comment