15

In Drupal 8+, how do I programmatically get a list of bundles for an entity type, for example the list of content types. Specifically, I'm looking for the machine names.

2 Answers 2

19

To get the bundles for an entity type, use the entity_type.bundle.info service.

$bundle_info = \Drupal::service('entity_type.bundle.info')->getBundleInfo($entity_type);

As usual, use dependency injection whenever possible.

See EntityTypeBundleInfo::getBundleInfo() for more information. In particular, see what the method returns.

An array of bundle information where the outer array is keyed by the bundle name, or the entity type name if the entity does not have bundles. The inner arrays are associative arrays of bundle information, such as the label for the bundle.

As example of Drupal core code that uses that service, see content_translation_entity_extra_field_info().

$extra = [];
$bundle_info_service = \Drupal::service('entity_type.bundle.info');
foreach (\Drupal::entityManager()->getDefinitions() as $entity_type => $info) {
  foreach ($bundle_info_service->getBundleInfo($entity_type) as $bundle => $bundle_info) {
    if (\Drupal::service('content_translation.manager')->isEnabled($entity_type, $bundle)) {
      $extra[$entity_type][$bundle]['form']['translation'] = [
        'label' => t('Translation'),
        'description' => t('Translation settings'),
        'weight' => 10,
      ];
    }
  }
}

return $extra;
1
  • This is the best approach. I believe It lacks bundle description and some additional information you need to fetch manually. Mar 23 at 20:42
6

If you want to get bundles of an entity type via drush the command is

drush php-eval "print_r(array_keys(\Drupal::service('entity_type.bundle.info')->getBundleInfo('ENTITY_TYPE')));"

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.