1

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;
}

I get the following error message:

Cannot access protected property Drupal\node\Entity\NodeType::$name

Hoe can I get the content type name?

2

To get a property, there is ConfigEntityBase::get(). Since ConfigEntityBase is a base class for NodeType, you can always use $value->get('name') to get the value of the name property.

0

name is the label of the node type entity, so you can get that with $node_type->label(). That works for any entity type, if what you want is specified as the label key in the entity type annotation.

-1

To get names of content type you can use below function

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.