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?

  • 1
    See EntityTypeRepositoryInterface::getEntityTypeLabels. Statically you can use \Drupal::service('entity_type.repository')->getEntityTypeLabels(). Non-statically is standard DI, which depends on the type of class you want to use it in. – 4k4 May 8 at 7:10
  • Googling drupal EntityManager is deprecated gives you a page full of samples how to accomplish this. Please always do some research first, try out what you find and if somethings left unclear provide a reproducible and detailed question of what went wrong. Many thanks – leymannx May 8 at 10:17
  • Yup. Did research, and look through code. EntityTypeManager does the job when you have an entity in mind... not so much when you want all entity types, which is where my research yielded the class I asked about. – JAyenGreen May 8 at 11:41

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();
| improve this answer | |
  • I asked about the other class because EntityTypeManager seems not have a GetDefinitions (plural) method, which is how I eventually found the EnitityTypeRepository class mentioned. – JAyenGreen May 8 at 11:46
  • It does have the getDefinitions() plutal method, so you're wrong about that. – No Sssweat May 8 at 23:23
  • 1
    You’re absolutely right. I forgot that there was an interim step where I read that I should instead be using the method getEntityTypeLabels instead, and it was it, not getDefinitions, that forced me to the other class. – JAyenGreen May 8 at 23:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.