You are here

public function ContentEntity::viewMultipleItems in Search API 8

Returns the render array for the provided items and view mode.

Parameters

\Drupal\Core\TypedData\ComplexDataInterface[] $items: The items to render.

string $view_mode: (optional) The view mode that should be used to render the items.

string|null $langcode: (optional) For which language the items should be rendered. Defaults to the language each item has been loaded in.

Return value

array A render array for displaying the items.

Overrides DatasourcePluginBase::viewMultipleItems

File

src/Plugin/search_api/datasource/ContentEntity.php, line 1018

Class

ContentEntity
Represents a datasource which exposes the content entities.

Namespace

Drupal\search_api\Plugin\search_api\datasource

Code

public function viewMultipleItems(array $items, $view_mode, $langcode = NULL) {
  try {
    $view_builder = $this
      ->getEntityTypeManager()
      ->getViewBuilder($this
      ->getEntityTypeId());

    // Langcode passed, use that for viewing.
    if (isset($langcode)) {
      $entities = [];
      foreach ($items as $i => $item) {
        if ($entity = $this
          ->getEntity($item)) {
          $entities[$i] = $entity;
        }
      }
      if ($entities) {
        return $view_builder
          ->viewMultiple($entities, $view_mode, $langcode);
      }
      return [];
    }

    // Otherwise, separate the items by language, keeping the keys.
    $items_by_language = [];
    foreach ($items as $i => $item) {
      if ($entity = $this
        ->getEntity($item)) {
        $items_by_language[$entity
          ->language()
          ->getId()][$i] = $entity;
      }
    }

    // Then build the items for each language. We initialize $build beforehand
    // and use array_replace() to add to it so the order stays the same.
    $build = array_fill_keys(array_keys($items), []);
    foreach ($items_by_language as $langcode => $language_items) {
      $build = array_replace($build, $view_builder
        ->viewMultiple($language_items, $view_mode, $langcode));
    }
    return $build;
  } catch (\Exception $e) {

    // The most common reason for this would be a
    // \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException in
    // getViewBuilder(), because the entity type definition doesn't specify a
    // view_builder class.
    return [];
  }
}