8

I'm using hook_ENTITY_TYPE_presave() to alter the values of nodes upon saving, but I only want to do this for a specific content type.

How do I check the content type of the $entity object? I looked at the documentation for class node and working with Entity API, but all I found was how to get the entity type, not the content type.

Given a node $entity object, how can I check the content type?

2 Answers 2

18

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.

1
  • Thanks for the answer! But is it possible to get the human readable value or it has to be str_replaced in order get there?
    – Alimba
    Jul 5, 2021 at 12:56
9

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.

Your Answer

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

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