10

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.

18

loadMultiple() should be fine for this:

$types = \Drupal::entityTypeManager()
  ->getStorage('node_type')
  ->loadMultiple();
12

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();
}
  • 2
    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 May 2 '16 at 19:04
0

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.

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.