Thursday 20 April 2017

Drupal 8 Get the list of all voacbs

To get the list of all vocabs, Drupal 7 provides us a function "taxonomy_vocabulary_get_names()" which return a list of all vocabs 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\taxonomy\Entity\Vocabulary;

then write this line, which returen an array of menu objects.
$vocabs_types = Vocabulary::loadMultiple();

For only get list of vocabs, you can use this

  $vocabs = array();
    $vocabs_types = Vocabulary::loadMultiple();

    if (!empty($vocabs_types)) {
      foreach ($vocabs_types as $vocab_name => $vocab) {
        $vocabs[$vocab_name] = $vocab->label();
      }
      asort($vocabs);
    }

No comments:

Post a Comment

Thanks!