How to programmatically get content type name in Drupal 8

Rahul Seth picture Rahul Seth · Jun 29, 2015 · Viewed 17.4k times · Source

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

Answer

Jose D Jo picture Jose D Jo · May 31, 2016

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')