19

How do I get a list of all the content types defined in a Drupal 8 site?

In Drupal 7 it used to be node_type_get_types(), but it has been deprecated.

I tried Entity::loadMultiple() but it doesn't seem to work. I was thinking about making a custom query, but I don't know how it's stored in the database.

5 Answers 5

35

loadMultiple() should be fine for this:

$types = \Drupal::entityTypeManager()
  ->getStorage('node_type')
  ->loadMultiple();
2
  • Not working on Drupal 8.9.x. Use stackoverflow.com/a/38252706/195812 instead
    – Augusto
    Commented Aug 27, 2020 at 7:04
  • 2
    This still works fine in Drupal 8.9 @augusto. The other post you’ve linked to is not the same question - this is for loading the node type config entities, not nodes.
    – Clive
    Commented Aug 27, 2020 at 7:56
20

You can load all of the NodeType entities (config entities) using the NodeType class:

$node_types = \Drupal\node\Entity\NodeType::loadMultiple();
// If you need to display them in a drop down:
$options = [];
foreach ($node_types as $node_type) {
  $options[$node_type->id()] = $node_type->label();
}
1
  • 3
    The trick with the static loadMultiple(), load(), and create() methods is to call them on the entity type class that you want to use, then it figures out the type and uses does the above dynamically. This is a bit shorter and easier to use, but it's recommended to use injected services when possible, so in a service/controller/plugin, you'd inject the entity type manager and then use that. Allows for easier (unit) testing but the result is more or less the same.
    – Berdir
    Commented May 2, 2016 at 19:04
3

There is another Drupal helper function that is not deprecated as of 8.7. node_type_get_names() returns:

string[] An array of node type labels, keyed by the node type name.

API docs

1
  • This is the easiest solution if you need to fill form select (or checkboxes) options.
    – TytooF
    Commented Oct 4, 2019 at 10:22
1

Provided in case node_type_get_names() gets deprecated in the future (also a nice example of array_map usage):

function node_type_get_names() {
  return array_map(function ($bundle_info) {
    return $bundle_info['label'];
  }, \Drupal::service('entity_type.bundle.info')
    ->getBundleInfo('node'));
}
1

There's a service for that called "entity_type.bundle.info":

>>> $bi = \Drupal::service('entity_type.bundle.info');
=> Drupal\Core\Entity\EntityTypeBundleInfo {#1433
     +"_serviceId": "entity_type.bundle.info",
   }
>>> $bi->getBundleInfo('node');
=> [
     "article" => [
       "label" => "Article",
       "translatable" => false,
     ],
.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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