How to get a list of entity types the Drupal 9 way?
题
I need to get a list of all entity types.
EntityManager is deprecated. In Drupal 9 EntityTypeRepository should be used, though I don't see any reference to its being used.
How would I use this class in a non-static way to obtain a list of all entity types?
解决方案
As the EntityManager docs say:
Deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal::entityTypeManager() instead in most cases. If the needed method is not on \Drupal\Core\Entity\EntityTypeManagerInterface, see the deprecated \Drupal\Core\Entity\EntityManager to find the correct interface or service.
$entity_type_manager = \Drupal::service('entity_type.manager');
$entity_definitions = $entity_type_manager->getDefinitions();
// Create a list of entity types.
$entity_types_list = [];
foreach($entity_definitions as $entity_name => $entity_definition) {
$entity_types_list[$entity_name] = (string) $entity_definition->getLabel();
}
不隶属于 drupal.stackexchange