Thursday 20 April 2017

Drupal 8 Get all content types

To get the list of all content type, Drupal 7 provides us a function "node_type_get_types()" which return a list of all content type with their machine name.
In D8 for some time this function will exist, but in future, this will be deprecated and in Drupal 9 this will be removed.
So if you are using this function then this will work but any update of Drupal 8 will deprecate this function.So to avoiding this problem use following code:

Just include this class
use Drupal\node\Entity\NodeType;

then write this line, which returen an array of content type objects.
$content_types = NodeType::loadMultiple();

For only get list of content type, you can use this

    $types = array();
    if (!empty($content_types)) {
      foreach ($content_types as $type => $details) {
        $types[$details->id()] = $details->label();
      }
      asort($types);
    }

No comments:

Post a Comment

Thanks!