function EntityTestController::listEntitiesAlphabetically

Same name in other branches
  1. 9 core/modules/system/tests/modules/entity_test/src/Controller/EntityTestController.php \Drupal\entity_test\Controller\EntityTestController::listEntitiesAlphabetically()
  2. 10 core/modules/system/tests/modules/entity_test/src/Controller/EntityTestController.php \Drupal\entity_test\Controller\EntityTestController::listEntitiesAlphabetically()
  3. 11.x core/modules/system/tests/modules/entity_test/src/Controller/EntityTestController.php \Drupal\entity_test\Controller\EntityTestController::listEntitiesAlphabetically()

List entities of the given entity type labels, sorted alphabetically.

Parameters

string $entity_type_id: The type of the entity being listed.

Return value

array A renderable array.

1 string reference to 'EntityTestController::listEntitiesAlphabetically'
entity_test.routing.yml in core/modules/system/tests/modules/entity_test/entity_test.routing.yml
core/modules/system/tests/modules/entity_test/entity_test.routing.yml

File

core/modules/system/tests/modules/entity_test/src/Controller/EntityTestController.php, line 63

Class

EntityTestController
Controller routines for entity_test routes.

Namespace

Drupal\entity_test\Controller

Code

public function listEntitiesAlphabetically($entity_type_id) {
    $entity_type_definition = $this->entityTypeManager()
        ->getDefinition($entity_type_id);
    $query = $this->entityTypeManager()
        ->getStorage($entity_type_id)
        ->getQuery();
    // Sort by label field, if any.
    if ($label_field = $entity_type_definition->getKey('label')) {
        $query->sort($label_field);
    }
    $entities = $this->entityTypeManager()
        ->getStorage($entity_type_id)
        ->loadMultiple($query->execute());
    $cache_tags = [];
    $labels = [];
    foreach ($entities as $entity) {
        $labels[] = $entity->label();
        $cache_tags = Cache::mergeTags($cache_tags, $entity->getCacheTags());
    }
    // Always associate the list cache tag, otherwise the cached empty result
    // wouldn't be invalidated. This would continue to show nothing matches the
    // query, even though a newly created entity might match the query.
    $cache_tags = Cache::mergeTags($cache_tags, $entity_type_definition->getListCacheTags());
    return [
        '#theme' => 'item_list',
        '#items' => $labels,
        '#title' => $entity_type_id . ' entities',
        '#cache' => [
            'contexts' => $entity_type_definition->getListCacheContexts(),
            'tags' => $cache_tags,
        ],
    ];
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.