emerico
11/28/2017 - 9:51 AM

Create vocabulary and term programmatically in drupal 8:- Drupal

Create vocabulary and term programmatically in drupal 8 Assing vocabulary to a referenced field storage automatically

<?php
    /** If vocabulary id not exist */
    if(!\Drupal\taxonomy\Entity\Vocabulary::load($vocab_id)){

      /**
       * Create vocabulary
       * @var $vocabulary
       */
      $vocabulary = \Drupal\taxonomy\Entity\Vocabulary::create([
        'vid' => $vocab_id,
        'description' => '',
        'name' => $node->getTitle()
      ])->save();

      /**
       * Create default term
       * @var $term
       */
      $term = \Drupal\taxonomy\Entity\Term::create([
        'name' => 'Default',
        'vid' => $vocab_id
      ])->save();

      /**
       * Attach vocabulary to field
       * @var $field_storage
       */
      $field_storage = \Drupal::entityManager()->getStorage('field_config')->loadByProperties(['field_name' => 'field_perspective_category']);
      $field_storage = $field_storage['node.factsheets.field_perspective_category'];
      $settings = $field_storage->getSetting('handler_settings');
      $settings['target_bundles'][$vocab_id] = $vocab_id;
      $field_storage->setSetting('handler_settings',$settings);
      $field_storage->save();
    }