Change record status: 
Project: 
Introduced in branch: 
8.x
Description: 

Summary

Drupal 8 introduces an entity view builder for rendering entities consistently. The view builder renders one or more entities in a given view mode and language, including attaching field data where appropriate.

API changes

Added interface and base class

The Drupal\Core\Entity\EntityViewBuilderInterface and Drupal\Core\Entity\EntityViewBuilder class have been added. Additionally, several core entity types subclass EntityViewBuilder for their rendering:

Custom entity types may use EntityViewBuilder directly or extend it.

Added functions

The following procedural API functions have been added:

Removed functions

The following functions have been removed in Drupal 8:

  • entity_prepare_view()
  • comment_build_content()
  • node_build_content()
  • taxonomy_term_show()
  • taxonomy_term_build_content()
  • user_build_content()

Examples

You can define a view builder for a given entity type by setting the 'view_builder' key in the EntityType 'controllers' annotation array and implementing EntityViewBuilderInterface (or extending EntityViewBuilder).


/**
 * @file
 * Contains \Drupal\my_module\Plugin\Core\Entity\MyEntity.
 */

namespace Drupal\my_module\Plugin\Core\Entity;

use Drupal\Core\Entity\Entity;
use Drupal\Core\Entity\Annotation\EntityType;
use Drupal\Core\Annotation\Translation;
use Drupal\my_module\MyEntityInterface;

/**
 * Defines a custom entity.
 *
 * @EntityType(
 *   id = "my_entity",
 *   label = @Translation("My entity"),
 *   controllers = {
 *     "storage" = "Drupal\Core\Entity\DatabaseStorageController",
 *     "view_builder" = "Drupal\my_module\MyViewBuilder"
 *   },
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label"
 *     "uuid" = "uuid"
 *   }
 * )
 */
class MyEntity extends Entity implements MyEntityInterface {
}
namespace Drupal\my_module;

use Drupal\Core\Entity\EntityViewBuilder;

/**
 * Defines the view builder for my_entity_type entities.
 */
class MyViewBuilder extends EntityViewBuilder {}

To render an entity, simply call the view() or viewMultiple() methods:

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('my_entity_type');

$full_output = $view_builder->view($entity);

$rss_output = $view_builder->view($entity, 'rss');

Impacts: 
Module developers