Same name and namespace in other branches
  1. 8.9.x core/lib/Drupal/Core/Entity/EntityListBuilder.php \Drupal\Core\Entity\EntityListBuilder
  2. 9 core/lib/Drupal/Core/Entity/EntityListBuilder.php \Drupal\Core\Entity\EntityListBuilder

Defines a generic implementation to build a listing of entities.

Hierarchy

Expanded class hierarchy of EntityListBuilder

Related topics

10 files declare their use of EntityListBuilder
BlockContentListBuilder.php in core/modules/block_content/src/BlockContentListBuilder.php
ConfigEntityListBuilder.php in core/lib/Drupal/Core/Config/Entity/ConfigEntityListBuilder.php
EntityListBuilderTest.php in core/tests/Drupal/Tests/Core/Entity/EntityListBuilderTest.php
EntityTestListBuilder.php in core/modules/system/tests/modules/entity_test/src/EntityTestListBuilder.php
MediaListBuilder.php in core/modules/media/src/MediaListBuilder.php

... See full list

File

core/lib/Drupal/Core/Entity/EntityListBuilder.php, line 17

Namespace

Drupal\Core\Entity
View source
class EntityListBuilder extends EntityHandlerBase implements EntityListBuilderInterface, EntityHandlerInterface {
  use MessengerTrait;
  use RedirectDestinationTrait;

  /**
   * The entity storage class.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $storage;

  /**
   * The entity type ID.
   *
   * @var string
   */
  protected $entityTypeId;

  /**
   * Information about the entity type.
   *
   * @var \Drupal\Core\Entity\EntityTypeInterface
   */
  protected $entityType;

  /**
   * The number of entities to list per page, or FALSE to list all entities.
   *
   * For example, set this to FALSE if the list uses client-side filters that
   * require all entities to be listed (like the views overview).
   *
   * @var int|false
   */
  protected $limit = 50;

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static($entity_type, $container
      ->get('entity_type.manager')
      ->getStorage($entity_type
      ->id()));
  }

  /**
   * Constructs a new EntityListBuilder object.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   * @param \Drupal\Core\Entity\EntityStorageInterface $storage
   *   The entity storage class.
   */
  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage) {
    $this->entityTypeId = $entity_type
      ->id();
    $this->storage = $storage;
    $this->entityType = $entity_type;
  }

  /**
   * {@inheritdoc}
   */
  public function getStorage() {
    return $this->storage;
  }

  /**
   * {@inheritdoc}
   */
  public function load() {
    $entity_ids = $this
      ->getEntityIds();
    return $this->storage
      ->loadMultiple($entity_ids);
  }

  /**
   * Loads entity IDs using a pager sorted by the entity id.
   *
   * @return array
   *   An array of entity IDs.
   */
  protected function getEntityIds() {
    return $this
      ->getEntityListQuery()
      ->execute();
  }

  /**
   * Returns a query object for loading entity IDs from the storage.
   *
   * @return \Drupal\Core\Entity\Query\QueryInterface
   *   A query object used to load entity IDs.
   */
  protected function getEntityListQuery() : QueryInterface {
    $query = $this
      ->getStorage()
      ->getQuery()
      ->accessCheck(TRUE)
      ->sort($this->entityType
      ->getKey('id'));

    // Only add the pager if a limit is specified.
    if ($this->limit) {
      $query
        ->pager($this->limit);
    }
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function getOperations(EntityInterface $entity) {
    $operations = $this
      ->getDefaultOperations($entity);
    $operations += $this
      ->moduleHandler()
      ->invokeAll('entity_operation', [
      $entity,
    ]);
    $this->moduleHandler
      ->alter('entity_operation', $operations, $entity);
    uasort($operations, '\\Drupal\\Component\\Utility\\SortArray::sortByWeightElement');
    return $operations;
  }

  /**
   * Gets this list's default operations.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity the operations are for.
   *
   * @return array
   *   The array structure is identical to the return value of
   *   self::getOperations().
   */
  protected function getDefaultOperations(EntityInterface $entity) {
    $operations = [];
    if ($entity
      ->access('update') && $entity
      ->hasLinkTemplate('edit-form')) {
      $edit_url = $this
        ->ensureDestination($entity
        ->toUrl('edit-form'));
      if (!empty($entity
        ->label())) {
        $label = $this
          ->t('Edit @entity_label', [
          '@entity_label' => $entity
            ->label(),
        ]);
      }
      else {
        $label = $this
          ->t('Edit @entity_bundle @entity_id', [
          '@entity_bundle' => $entity
            ->bundle(),
          '@entity_id' => $entity
            ->id(),
        ]);
      }
      $attributes = $edit_url
        ->getOption('attributes') ?: [];
      $attributes += [
        'aria-label' => $label,
      ];
      $edit_url
        ->setOption('attributes', $attributes);
      $operations['edit'] = [
        'title' => $this
          ->t('Edit'),
        'weight' => 10,
        'url' => $edit_url,
      ];
    }
    if ($entity
      ->access('delete') && $entity
      ->hasLinkTemplate('delete-form')) {
      $delete_url = $this
        ->ensureDestination($entity
        ->toUrl('delete-form'));
      if (!empty($entity
        ->label())) {
        $label = $this
          ->t('Delete @entity_label', [
          '@entity_label' => $entity
            ->label(),
        ]);
      }
      else {
        $label = $this
          ->t('Delete @entity_bundle @entity_id', [
          '@entity_bundle' => $entity
            ->bundle(),
          '@entity_id' => $entity
            ->id(),
        ]);
      }
      $attributes = $delete_url
        ->getOption('attributes') ?: [];
      $attributes += [
        'aria-label' => $label,
      ];
      $delete_url
        ->setOption('attributes', $attributes);
      $operations['delete'] = [
        'title' => $this
          ->t('Delete'),
        'weight' => 100,
        'attributes' => [
          'class' => [
            'use-ajax',
          ],
          'data-dialog-type' => 'modal',
          'data-dialog-options' => Json::encode([
            'width' => 880,
          ]),
        ],
        'url' => $delete_url,
      ];
    }
    return $operations;
  }

  /**
   * Builds the header row for the entity listing.
   *
   * @return array
   *   A render array structure of header strings.
   *
   * @see \Drupal\Core\Entity\EntityListBuilder::render()
   */
  public function buildHeader() {
    $row['operations'] = $this
      ->t('Operations');
    return $row;
  }

  /**
   * Builds a row for an entity in the entity listing.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity for this row of the list.
   *
   * @return array
   *   A render array structure of fields for this entity.
   *
   * @see \Drupal\Core\Entity\EntityListBuilder::render()
   */
  public function buildRow(EntityInterface $entity) {
    $row['operations']['data'] = $this
      ->buildOperations($entity);
    return $row;
  }

  /**
   * Builds a renderable list of operation links for the entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity on which the linked operations will be performed.
   *
   * @return array
   *   A renderable array of operation links.
   *
   * @see \Drupal\Core\Entity\EntityListBuilder::buildRow()
   */
  public function buildOperations(EntityInterface $entity) {
    $build = [
      '#type' => 'operations',
      '#links' => $this
        ->getOperations($entity),
      // Allow links to use modals.
      '#attached' => [
        'library' => [
          'core/drupal.dialog.ajax',
        ],
      ],
    ];
    return $build;
  }

  /**
   * {@inheritdoc}
   *
   * Builds the entity listing as renderable array for table.html.twig.
   *
   * @todo Add a link to add a new item to the #empty text.
   */
  public function render() {
    $build['table'] = [
      '#type' => 'table',
      '#header' => $this
        ->buildHeader(),
      '#title' => $this
        ->getTitle(),
      '#rows' => [],
      '#empty' => $this
        ->t('There are no @label yet.', [
        '@label' => $this->entityType
          ->getPluralLabel(),
      ]),
      '#cache' => [
        'contexts' => $this->entityType
          ->getListCacheContexts(),
        'tags' => $this->entityType
          ->getListCacheTags(),
      ],
    ];
    foreach ($this
      ->load() as $entity) {
      if ($row = $this
        ->buildRow($entity)) {
        $build['table']['#rows'][$entity
          ->id()] = $row;
      }
    }

    // Only add the pager if a limit is specified.
    if ($this->limit) {
      $build['pager'] = [
        '#type' => 'pager',
      ];
    }
    return $build;
  }

  /**
   * Gets the title of the page.
   */
  protected function getTitle() {
  }

  /**
   * Ensures that a destination is present on the given URL.
   *
   * @param \Drupal\Core\Url $url
   *   The URL object to which the destination should be added.
   *
   * @return \Drupal\Core\Url
   *   The updated URL object.
   */
  protected function ensureDestination(Url $url) {
    return $url
      ->mergeOptions([
      'query' => $this
        ->getRedirectDestination()
        ->getAsArray(),
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
EntityHandlerBase::$moduleHandler protected property The module handler to invoke hooks on. 5
EntityHandlerBase::moduleHandler protected function Gets the module handler. 5
EntityHandlerBase::setModuleHandler public function Sets the module handler for this handler.
EntityListBuilder::$entityType protected property Information about the entity type.
EntityListBuilder::$entityTypeId protected property The entity type ID.
EntityListBuilder::$limit protected property The number of entities to list per page, or FALSE to list all entities.
EntityListBuilder::$storage protected property The entity storage class. 2
EntityListBuilder::buildHeader public function Builds the header row for the entity listing. 20
EntityListBuilder::buildOperations public function Builds a renderable list of operation links for the entity. 1
EntityListBuilder::buildRow public function Builds a row for an entity in the entity listing. 20
EntityListBuilder::createInstance public static function Instantiates a new instance of this entity handler. Overrides EntityHandlerInterface::createInstance 12
EntityListBuilder::ensureDestination protected function Ensures that a destination is present on the given URL. 1
EntityListBuilder::getDefaultOperations protected function Gets this list's default operations. 3
EntityListBuilder::getEntityIds protected function Loads entity IDs using a pager sorted by the entity id. 5
EntityListBuilder::getEntityListQuery protected function Returns a query object for loading entity IDs from the storage.
EntityListBuilder::getOperations public function Provides an array of information to build a list of operation links. Overrides EntityListBuilderInterface::getOperations 2
EntityListBuilder::getStorage public function Gets the entity storage. Overrides EntityListBuilderInterface::getStorage 1
EntityListBuilder::getTitle protected function Gets the title of the page. 1
EntityListBuilder::load public function Loads entities of this type from storage for listing. Overrides EntityListBuilderInterface::load 3
EntityListBuilder::render public function Builds the entity listing as renderable array for table.html.twig. Overrides EntityListBuilderInterface::render 14
EntityListBuilder::__construct public function Constructs a new EntityListBuilder object. 12
MessengerTrait::$messenger protected property The messenger. 10
MessengerTrait::messenger public function Gets the messenger. 10
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 1
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.