11

I'm working on Drupal 8. And I want to get content type machine name and label. Here is my code:

$cont_type = node_type_get_types();
foreach ($cont_type as $key => $value) {
  $label = $value->name;
  $machine_name = $key;
}

Here I got an error message : Cannot access protected property Drupal\node\Entity\NodeType::$name

Rahul Seth
  • 415
  • 1
  • 5
  • 14

7 Answers7

17

In order to get current content type:

$node = \Drupal::routeMatch()->getParameter('node');
$typeName = $node->bundle();
$typeLabel = $node->getTitle();

There is an alternative method.

$node = \Drupal::request()->attributes->get('node')
Jose D
  • 489
  • 3
  • 5
  • Welcome Jose! Try to explain what your code does to make it a better answer! You should read this http://stackoverflow.com/help/how-to-answer – David May 31 '16 at 11:07
9
<?php
  use Drupal\node\Entity\NodeType;
?>

<?php
  $all_content_types = NodeType::loadMultiple();
  /** @var NodeType $content_type */
  foreach ($all_content_types as $machine_name => $content_type) {
    $label = $content_type->label();
  }
?>
ebeyrent
  • 413
  • 5
  • 7
4

Solved using this code in template_preprocess_node()

$content_type = $node->type->entity->label();
Thirsty Six
  • 399
  • 1
  • 6
  • 13
1
$entityTypeManager = \Drupal::service('entity_type.manager');

$types = [];
$contentTypes = $entityTypeManager->getStorage('node_type')->loadMultiple();
foreach ($contentTypes as $contentType) {
  $types[$contentType->id()] = $contentType->label();
}
0

The NodeType class inherits the label() method from the Entity class, use that function to get the content type label. See Entity::label.

$label = $value->label();
baikho
  • 5,203
  • 4
  • 40
  • 47
-1

use {{ node.field_name.fieldDefinition.label }}

  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Jun 17 '21 at 07:48
-3

Please use the namespace

use Drupal\node\Entity\Node;