3 namespace Drupal\Core\Entity;
5 use Drupal\Component\Utility\Crypt;
6 use Drupal\Core\Cache\Cache;
7 use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
8 use Drupal\Core\Entity\Entity\EntityViewDisplay;
9 use Drupal\Core\Field\FieldItemInterface;
10 use Drupal\Core\Field\FieldItemListInterface;
11 use Drupal\Core\Language\LanguageManagerInterface;
12 use Drupal\Core\Render\Element;
13 use Drupal\Core\Theme\Registry;
14 use Drupal\Core\TypedData\TranslatableInterface;
15 use Symfony\Component\DependencyInjection\ContainerInterface;
18 * Base class for entity view builders.
22 class EntityViewBuilder extends EntityHandlerBase implements EntityHandlerInterface, EntityViewBuilderInterface {
25 * The type of entities for which this view builder is instantiated.
29 protected $entityTypeId;
32 * Information about the entity type.
34 * @var \Drupal\Core\Entity\EntityTypeInterface
36 protected $entityType;
39 * The entity manager service.
41 * @var \Drupal\Core\Entity\EntityManagerInterface
43 protected $entityManager;
46 * The cache bin used to store the render cache.
50 protected $cacheBin = 'render';
53 * The language manager.
55 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
57 protected $languageManager;
62 * @var \Drupal\Core\Theme\Registry
64 protected $themeRegistry;
67 * The EntityViewDisplay objects created for individual field rendering.
69 * @see \Drupal\Core\Entity\EntityViewBuilder::getSingleFieldDisplay()
71 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface[]
73 protected $singleFieldDisplays;
76 * Constructs a new EntityViewBuilder.
78 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
79 * The entity type definition.
80 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
81 * The entity manager service.
82 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
83 * The language manager.
84 * @param \Drupal\Core\Theme\Registry $theme_registry
87 public function __construct(EntityTypeInterface $entity_type, EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, Registry $theme_registry = NULL) {
88 $this->entityTypeId = $entity_type->id();
89 $this->entityType = $entity_type;
90 $this->entityManager = $entity_manager;
91 $this->languageManager = $language_manager;
92 $this->themeRegistry = $theme_registry ?: \Drupal::service('theme.registry');
98 public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
101 $container->get('entity.manager'),
102 $container->get('language_manager'),
103 $container->get('theme.registry')
110 public function view(EntityInterface $entity, $view_mode = 'full', $langcode = NULL) {
111 $build_list = $this->viewMultiple([$entity], $view_mode, $langcode);
113 // The default ::buildMultiple() #pre_render callback won't run, because we
114 // extract a child element of the default renderable array. Thus we must
115 // assign an alternative #pre_render callback that applies the necessary
116 // transformations and then still calls ::buildMultiple().
117 $build = $build_list[0];
118 $build['#pre_render'][] = [$this, 'build'];
126 public function viewMultiple(array $entities = [], $view_mode = 'full', $langcode = NULL) {
129 '#pre_render' => [[$this, 'buildMultiple']],
132 foreach ($entities as $key => $entity) {
133 // Ensure that from now on we are dealing with the proper translation
135 $entity = $this->entityManager->getTranslationFromContext($entity, $langcode);
137 // Set build defaults.
138 $build_list[$key] = $this->getBuildDefaults($entity, $view_mode);
139 $entityType = $this->entityTypeId;
140 $this->moduleHandler()->alter([$entityType . '_build_defaults', 'entity_build_defaults'], $build_list[$key], $entity, $view_mode);
142 $build_list[$key]['#weight'] = $weight++;
149 * Provides entity-specific defaults to the build process.
151 * @param \Drupal\Core\Entity\EntityInterface $entity
152 * The entity for which the defaults should be provided.
153 * @param string $view_mode
154 * The view mode that should be used.
158 protected function getBuildDefaults(EntityInterface $entity, $view_mode) {
159 // Allow modules to change the view mode.
161 $this->moduleHandler()->alter('entity_view_mode', $view_mode, $entity, $context);
164 "#{$this->entityTypeId}" => $entity,
165 '#view_mode' => $view_mode,
166 // Collect cache defaults for this entity.
168 'tags' => Cache::mergeTags($this->getCacheTags(), $entity->getCacheTags()),
169 'contexts' => $entity->getCacheContexts(),
170 'max-age' => $entity->getCacheMaxAge(),
174 // Add the default #theme key if a template exists for it.
175 if ($this->themeRegistry->getRuntime()->has($this->entityTypeId)) {
176 $build['#theme'] = $this->entityTypeId;
179 // Cache the rendered output if permitted by the view mode and global entity
180 // type configuration.
181 if ($this->isViewModeCacheable($view_mode) && !$entity->isNew() && $entity->isDefaultRevision() && $this->entityType->isRenderCacheable()) {
182 $build['#cache'] += [
189 'bin' => $this->cacheBin,
192 if ($entity instanceof TranslatableInterface && count($entity->getTranslationLanguages()) > 1) {
193 $build['#cache']['keys'][] = $entity->language()->getId();
201 * Builds an entity's view; augments entity defaults.
203 * This function is assigned as a #pre_render callback in ::view().
205 * It transforms the renderable array for a single entity to the same
206 * structure as if we were rendering multiple entities, and then calls the
207 * default ::buildMultiple() #pre_render callback.
209 * @param array $build
210 * A renderable array containing build information and context for an entity
214 * The updated renderable array.
216 * @see drupal_render()
218 public function build(array $build) {
219 $build_list = [$build];
220 $build_list = $this->buildMultiple($build_list);
221 return $build_list[0];
225 * Builds multiple entities' views; augments entity defaults.
227 * This function is assigned as a #pre_render callback in ::viewMultiple().
229 * By delaying the building of an entity until the #pre_render processing in
230 * drupal_render(), the processing cost of assembling an entity's renderable
231 * array is saved on cache-hit requests.
233 * @param array $build_list
234 * A renderable array containing build information and context for an
238 * The updated renderable array.
240 * @see drupal_render()
242 public function buildMultiple(array $build_list) {
243 // Build the view modes and display objects.
245 $entity_type_key = "#{$this->entityTypeId}";
246 $view_hook = "{$this->entityTypeId}_view";
248 // Find the keys for the ContentEntities in the build; Store entities for
249 // rendering by view_mode.
250 $children = Element::children($build_list);
251 foreach ($children as $key) {
252 if (isset($build_list[$key][$entity_type_key])) {
253 $entity = $build_list[$key][$entity_type_key];
254 if ($entity instanceof FieldableEntityInterface) {
255 $view_modes[$build_list[$key]['#view_mode']][$key] = $entity;
260 // Build content for the displays represented by the entities.
261 foreach ($view_modes as $view_mode => $view_mode_entities) {
262 $displays = EntityViewDisplay::collectRenderDisplays($view_mode_entities, $view_mode);
263 $this->buildComponents($build_list, $view_mode_entities, $displays, $view_mode);
264 foreach (array_keys($view_mode_entities) as $key) {
265 // Allow for alterations while building, before rendering.
266 $entity = $build_list[$key][$entity_type_key];
267 $display = $displays[$entity->bundle()];
269 $this->moduleHandler()->invokeAll($view_hook, [&$build_list[$key], $entity, $display, $view_mode]);
270 $this->moduleHandler()->invokeAll('entity_view', [&$build_list[$key], $entity, $display, $view_mode]);
272 $this->alterBuild($build_list[$key], $entity, $display, $view_mode);
274 // Assign the weights configured in the display.
275 // @todo: Once https://www.drupal.org/node/1875974 provides the missing
276 // API, only do it for 'extra fields', since other components have
277 // been taken care of in EntityViewDisplay::buildMultiple().
278 foreach ($display->getComponents() as $name => $options) {
279 if (isset($build_list[$key][$name])) {
280 $build_list[$key][$name]['#weight'] = $options['weight'];
284 // Allow modules to modify the render array.
285 $this->moduleHandler()->alter([$view_hook, 'entity_view'], $build_list[$key], $entity, $display);
295 public function buildComponents(array &$build, array $entities, array $displays, $view_mode) {
296 $entities_by_bundle = [];
297 foreach ($entities as $id => $entity) {
298 // Initialize the field item attributes for the fields being displayed.
299 // The entity can include fields that are not displayed, and the display
300 // can include components that are not fields, so we want to act on the
301 // intersection. However, the entity can have many more fields than are
302 // displayed, so we avoid the cost of calling $entity->getProperties()
303 // by iterating the intersection as follows.
304 foreach ($displays[$entity->bundle()]->getComponents() as $name => $options) {
305 if ($entity->hasField($name)) {
306 foreach ($entity->get($name) as $item) {
307 $item->_attributes = [];
311 // Group the entities by bundle.
312 $entities_by_bundle[$entity->bundle()][$id] = $entity;
315 // Invoke hook_entity_prepare_view().
316 $this->moduleHandler()->invokeAll('entity_prepare_view', [$this->entityTypeId, $entities, $displays, $view_mode]);
318 // Let the displays build their render arrays.
319 foreach ($entities_by_bundle as $bundle => $bundle_entities) {
320 $display_build = $displays[$bundle]->buildMultiple($bundle_entities);
321 foreach ($bundle_entities as $id => $entity) {
322 $build[$id] += $display_build[$id];
328 * Specific per-entity building.
330 * @param array $build
331 * The render array that is being created.
332 * @param \Drupal\Core\Entity\EntityInterface $entity
333 * The entity to be prepared.
334 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
335 * The entity view display holding the display options configured for the
337 * @param string $view_mode
338 * The view mode that should be used to prepare the entity.
340 protected function alterBuild(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) { }
345 public function getCacheTags() {
346 return [$this->entityTypeId . '_view'];
352 public function resetCache(array $entities = NULL) {
353 // If no set of specific entities is provided, invalidate the entity view
354 // builder's cache tag. This will invalidate all entities rendered by this
356 // Otherwise, if a set of specific entities is provided, invalidate those
357 // specific entities only, plus their list cache tags, because any lists in
358 // which these entities are rendered, must be invalidated as well. However,
359 // even in this case, we might invalidate more cache items than necessary.
360 // When we have a way to invalidate only those cache items that have both
361 // the individual entity's cache tag and the view builder's cache tag, we'll
362 // be able to optimize this further.
363 if (isset($entities)) {
365 foreach ($entities as $entity) {
366 $tags = Cache::mergeTags($tags, $entity->getCacheTags());
367 $tags = Cache::mergeTags($tags, $entity->getEntityType()->getListCacheTags());
369 Cache::invalidateTags($tags);
372 Cache::invalidateTags($this->getCacheTags());
377 * Determines whether the view mode is cacheable.
379 * @param string $view_mode
380 * Name of the view mode that should be rendered.
383 * TRUE if the view mode can be cached, FALSE otherwise.
385 protected function isViewModeCacheable($view_mode) {
386 if ($view_mode == 'default') {
387 // The 'default' is not an actual view mode.
390 $view_modes_info = $this->entityManager->getViewModes($this->entityTypeId);
391 return !empty($view_modes_info[$view_mode]['cache']);
397 public function viewField(FieldItemListInterface $items, $display_options = []) {
398 $entity = $items->getEntity();
399 $field_name = $items->getFieldDefinition()->getName();
400 $display = $this->getSingleFieldDisplay($entity, $field_name, $display_options);
403 $build = $display->build($entity);
404 if (isset($build[$field_name])) {
405 $output = $build[$field_name];
414 public function viewFieldItem(FieldItemInterface $item, $display = []) {
415 $entity = $item->getEntity();
416 $field_name = $item->getFieldDefinition()->getName();
418 // Clone the entity since we are going to modify field values.
419 $clone = clone $entity;
421 // Push the item as the single value for the field, and defer to viewField()
422 // to build the render array for the whole list.
423 $clone->{$field_name}->setValue([$item->getValue()]);
424 $elements = $this->viewField($clone->{$field_name}, $display);
426 // Extract the part of the render array we need.
427 $output = isset($elements[0]) ? $elements[0] : [];
428 if (isset($elements['#access'])) {
429 $output['#access'] = $elements['#access'];
436 * Gets an EntityViewDisplay for rendering an individual field.
438 * @param \Drupal\Core\Entity\EntityInterface $entity
440 * @param string $field_name
442 * @param string|array $display_options
443 * The display options passed to the viewField() method.
445 * @return \Drupal\Core\Entity\Display\EntityViewDisplayInterface
447 protected function getSingleFieldDisplay($entity, $field_name, $display_options) {
448 if (is_string($display_options)) {
449 // View mode: use the Display configured for the view mode.
450 $view_mode = $display_options;
451 $display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);
452 // Hide all fields except the current one.
453 foreach (array_keys($entity->getFieldDefinitions()) as $name) {
454 if ($name != $field_name) {
455 $display->removeComponent($name);
460 // Array of custom display options: use a runtime Display for the
461 // '_custom' view mode. Persist the displays created, to reduce the number
462 // of objects (displays and formatter plugins) created when rendering a
463 // series of fields individually for cases such as views tables.
464 $entity_type_id = $entity->getEntityTypeId();
465 $bundle = $entity->bundle();
466 $key = $entity_type_id . ':' . $bundle . ':' . $field_name . ':' . Crypt::hashBase64(serialize($display_options));
467 if (!isset($this->singleFieldDisplays[$key])) {
468 $this->singleFieldDisplays[$key] = EntityViewDisplay::create([
469 'targetEntityType' => $entity_type_id,
472 ])->setComponent($field_name, $display_options);
474 $display = $this->singleFieldDisplays[$key];