Drupal 7 tip : Theming : Render only a single field of your entities

Posted by: 
Dominique De Cooman

If you want to render only one field of your entities you can in drupal 7. Here in the example we have an entity called model which contains an image field.

To render the field you have to specify to the field_attach_view function which entity type, the entity and the view mode you want to use. The function returns a renderable array.

Now you can even make adjustments to the array but it is advised that you use the settings forms that manages the display of your fields to stay consistent. In the example we change the image cache preset for our image.

Use the render function and give it the renderable array to obtain the html.

$render['field_headerimage_image'][$active_image]['#image_style'] = 'header_style';
$output render($render['field_headerimage_image'][$active_image]);

Using the field_attach_view will render all fields on your entity. Using the field_view_field function you can specify which field you want to render.

$field_to_render[$active_image]['#image_style'] = 'header_style';
$output render($field_to_render[$active_image]);

Add new comment