Last active
April 14, 2023 15:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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