Skip to content

Instantly share code, notes, and snippets.

@devudit
Last active April 14, 2023 15:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devudit/548de50a07ced35fedecdc09cf0652bd to your computer and use it in GitHub Desktop.
Save devudit/548de50a07ced35fedecdc09cf0652bd to your computer and use it in GitHub Desktop.
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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment