Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically get content type name in Drupal 8

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

like image 371
Rahul Seth Avatar asked Jun 29 '15 12:06

Rahul Seth


2 Answers

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')
like image 78
Jose D Jo Avatar answered Oct 20 '22 12:10

Jose D Jo


<?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();
  }
?>
like image 26
ebeyrent Avatar answered Oct 20 '22 14:10

ebeyrent