19

I'm trying to get the bundle label (node type label) of the node from a node object in Drupal 8.

This works, but seems long-winded:

$node_type = \Drupal::entityManager()->getStorage('node_type')->load($node->getType())->get('name');

Is there another way to get the bundle label, possible in a less complicated way?

2
  • 6
    $node->type->entity->label(); is a bit more graceful maybe? I'm not sure there's a shorter version currently
    – Clive
    Apr 28, 2016 at 17:13
  • 2
    Also works in twig template: {{ node.type.entity.label }}
    – oknate
    May 17, 2016 at 15:22

5 Answers 5

21

The following code works, as pointed out from @Clive.

$type_name = $node->type->entity->label();
2
  • Works for me. Thanks Nov 18, 2019 at 19:17
  • 1
    For anyone who needs to mock this, there's some magic going on. A magic __get method in ContentEntityBase which looks for type in it's fieldDefinitions array. The BaseFieldDefinition type is then returned as part of an EntityReferenceFieldItemList. Then another magic __get method in its base class FieldItemList, gets the first (and I think only) element of the list, which is an EntityReferenceItem, it then calls its own __get method to get the 'entity' property, which pulls an EntityReference from its own 'properties' array. Finally the label function is called from the EntityBase class.
    – Cameron
    Aug 1, 2022 at 11:11
14

In case you need the node type machine name in Twig template:

{{ node.getType }}
10

If you want the label in twig

{{ node.type.entity.label }}
7

Try this code.

use Drupal\node\Entity\NodeType;

$types = NodeType::loadMultiple();
$bundle = $node->bundle(); 
$type_name = $types[$bundle]->label();
3
  • 3
    That loads all node types just to get the label of one. a bit inefficient, better to just load the one you want.
    – Berdir
    May 13, 2016 at 7:51
  • Agree! It's just base on code of @No Sssweat.
    – MrD
    May 13, 2016 at 10:19
  • @Berdir thx for pointing that out. I don't want to chameleon the question, so I will leave this as the accepted answer. I am using the code in my own answer instead.
    – No Sssweat
    May 14, 2016 at 10:42
2

There is a function for that

node_get_type_label($node);

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.