Render a single field of an entity

Posted by patrick on Mon, 04/03/2017 - 12:41

Sometimes you just want to get the renderable array of a single field of an entity instead of the full entity. In the example below, we'll get the renderable array for two fields, body and field_example:

use Drupal\node\Entity\Node;
 
$render = [];
$entity_type_manager = \Drupal::entityTypeManager();
$entity = $entity_type_manager->getStorage($entity_type)->load($entity_id);
$fields = [
  'body',
  'field_example'
];
if ($entity) {
  $display = $entity_type_manager->getStorage('entity_view_display')->load($entity_type . '.' . $entity->bundle() . '.' . $view_mode);
  $view_builder = NULL;
  foreach ($fields as $field_name) {
    if (isset($entity->{$field_name})) {
      $component = $display->getComponent($field_name);
      if ($component) {
        if ($view_builder === NULL) {
          $view_builder = $entity_type_manager->getViewBuilder($entity_type);
        }
        $render[$field_name] = $view_builder->viewField($entity->{$field_name}, $display->getComponent($field_name));
      }
    }
  }
}

First we load the entity object and create an array containing the machine-readable names of the fields we want to render. Then we'll load the entity view display for a view mode of the entity, that contains display settings for the fields we want to render. We'll also need the view builder for the entity type. Then, we'll get the display settings for each field from the display using the getComponent() method and provide it to the viewField() method of the view builder along with the actual contents of the field. This will return a renderable array for the field, that can be printed in a template or rendered using the Renderer service.

If you don't have a fitting view mode, you could also provide the display settings yourself. Basically, it consists of information about how to display or not display the field label, the id of the field formatter to use and any settings, the field formatter might need. Look at the documentation for the viewField() method linked above for more information, if you need that.

Update: Should you only need to occasionally render a single field already at hand, you can also use the Drupal\Core\Field\FieldItemList::view method of the field itself, e.g.:

$build = $entity->field_example->view('teaser');

A display options array can also be passed to the method instead of the view mode name..

Systems
Drupal 8