Rahul Seth
Rahul Seth

Reputation: 453

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

Upvotes: 13

Views: 32137

Answers (7)

Mohammad Seifi
Mohammad Seifi

Reputation: 21

$entityTypeManager = \Drupal::service('entity_type.manager');

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

Upvotes: 2

Thirsty Six
Thirsty Six

Reputation: 489

Solved using this code in template_preprocess_node()

$content_type = $node->type->entity->label();

Upvotes: 6

Sunnysinh Thakor
Sunnysinh Thakor

Reputation: 1

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

Upvotes: -1

Rahulmon Johnson
Rahulmon Johnson

Reputation: 1

Please use the namespace

use Drupal\node\Entity\Node;

Upvotes: -3

Jose D
Jose D

Reputation: 499

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

Upvotes: 18

ebeyrent
ebeyrent

Reputation: 413

<?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();
  }
?>

Upvotes: 9

baikho
baikho

Reputation: 5368

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();

Upvotes: 0

Related Questions