Drupal - How do I get the content type of a node entity from the $entity object?

If you know that you have a node, then you can use getType(). If you don't know that, you can use he generic method ->bundle(). Note that the second will return the entity type in case of an entity type that doesn't have bundles, like users.

Again, my standard reference to http://wizzlern.nl/sites/wizzlern.nl/files/artikel/drupal-content-entity-8.0.pdf, it contains both methods.


Entity Type and bundle name are two things; usually you want to have both. You might e.g. have a media entity of the bundle "image". Bundle names alone may not be unique, I think you could name a content type "gallery" and also a paragraph type "gallery" without getting a validation error. So:

$entity->getEntityTypeId()

gives you the entity type: node, user, paragraph, media

$entity->bundle()

gives you the bundle name if you have one, could be "gallery" like described above. As Berdir points out, getType() only works on nodes, so getEntityTypeId() would be a replacement for that that works on all entity types.

Tags:

Entities

Nodes

8