Skip to content

Instantly share code, notes, and snippets.

@BBGuy
Last active March 15, 2023 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BBGuy/5eff0092b73ef446ffdce02b2a3c32b4 to your computer and use it in GitHub Desktop.
Save BBGuy/5eff0092b73ef446ffdce02b2a3c32b4 to your computer and use it in GitHub Desktop.
Drupal 9 - Working with Taxonomy Entities
<?php
// Util functions to load a select lists options from a taxonomy or a node field with a text list.
function build_form() {
$form = [];
// Load a two level deep select tree from a taxonomy
$options = load_taxonomy_as_select_options('example_taxonomy');
$form['select_tree'] = [
'#type' => 'select',
'#title' => $this->t('Taxonomy Tree Select'),
'#options' => $options,
'#size' => 1,
];
// Load a thes select options from a node text list field.
$options = load_node_field_options_as_select_options('news_artical', 'artical_type_field');
$form['select_field'] = [
'#type' => 'select',
'#title' => $this->t('Field Select Options'),
'#options' => $options,
'#size' => 1,
];
}
function load_taxonomy_as_select_options($vid, $required = FALSE) {
// We only support two levels
$taxonomy_tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, 0, 2);
$options = [];
$current_element = &$options;
if (!$required) {
$options['All'] = t('- Any -');
}
foreach ($taxonomy_tree as $key => $term) {
if ($term->depth == 0) {
$options[$term->name] = [];
$current_element = &$options[$term->name];
}
else {
$current_element[$term->tid] = $term->name;
}
}
return $options;
}
function load_node_field_options_as_select_options($node_name, $field_name, $required = FALSE) {
$options = [];
if (!$required) {
$options['All'] = t('- Any -');
}
$field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', $node_name);
if (isset($field_definitions[$field_name])) {
$options += options_allowed_values($field_definitions[$field_name]->getFieldStorageDefinition());
}
return $options;
}
<?php
// Commonly used functions and code snippets.
// Get the vocabulary ID.
$vocabularies = taxonomy_vocabulary_get_names(); // Deprecated
$vocabularies = \Drupal::entityQuery('taxonomy_vocabulary')->execute(); // use this
$vid = array_search($taxonomy_name, 'tags');
echo $vid // output: tags
// Set a single value taxonomy reference field.
$entity->set('field_taxonomy_term_ref', 3);
// Set multiple values taxonomy reference field.
$entity->set('field_taxonomy_term_ref', [3,4,7]);
// Clear a taxonomy reference field.
$entity->set('field_taxonomy_term_ref', NULL);
// Load a term using its ID.
/** @var \Drupal\taxonomy\Entity\Term $term */
$term = \Drupal\taxonomy\Entity\Term::load($term_id)
// Load a term using its name.
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')
->loadByProperties(['name' => $term_name, 'vid' => 'tags']);
// Using Entity query.
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('vid', "tags");
$query->condition('name', $term_name);
$tids = $query->execute();
// Load a term using a custom field.
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')
->loadByProperties(['field_custom_name' => 'internal-id-12345', 'vid' => 'my_special_terms']);
// Make sure only one
if (count($terms) == 1) {
/** @var \Drupal\taxonomy\Entity\Term $term */
$term = array_pop($terms);
}
// Cycle
foreach ($terms as $term) {
$term_id = $term->id();
$term_name = $term->getName();
}
// Nested refrences
// Does the node have a taxonomy term reference
if ($node->hasField('field_my_taxonomy_ref') && (!$node->get("field_my_taxonomy_ref")->isEmpty())) {
$term_id = $node->field_my_taxonomy_ref->target_id;
// This check should not be needed as we already checked it is not empty.
if (isset($term_id)) {
// Load the term and get details
$term = \Drupal\taxonomy\Entity\Term::load($term_id);
$term_name = $term->name->value;
// If the term has a taxonomy term reference itself.
$another_term_tid = $term->field_another_taxonomy_ref->target_id;
$another_term = \Drupal\taxonomy\Entity\Term::load($another_term_tid);
$another_term_name = $another_term->name->value;
}
}
}
//********** Get Term data. ***********//
/** @var \Drupal\taxonomy\Entity\Term $term */
$term = \Drupal\taxonomy\Entity\Term::load($tid);
// Get the name & description
$term_name = $term->getName();
$term_description = $term->getDescription())
// get the bundle name / VID
$bundle_name = $term->bundle();
// Get a field value (array)
$my_field = $term->field_my_field->getValue();
// Get as a single value.
$my_field = $term->field_my_field->value;
//********** Create ***********//
$term_data = [
'vid' => 'vocabulary',
'name' => 'tag name',
];
$term = \Drupal\taxonomy\Entity\Term::create($term_data);
$term->save();
// more options from https://www.drupal8.ovh/en/tutoriels/55/create-taxonomy-term-programmatically-on-drupal-8
$term_data = [
'vid' => 'test_vocabulary',
'langcode' => 'en',
'name' => 'My tag',
'description' => [
'value' => '<p>My description.</p>',
'format' => 'full_html',
],
'weight' => -1,
'parent' => array(0),
]);
// Create the taxonomy.
$attribute_machine_name = "new_vocabulary";
$vocabularies = \Drupal\taxonomy\Entity\Vocabulary::loadMultiple();
if (!isset($vocabularies[$attribute_machine_name])) {
$vocabulary = \Drupal\taxonomy\Entity\Vocabulary::create(array(
'vid' => $attribute_machine_name,
'description' => "a test Vocabulary",
'name' => "New Vocabulary",
));
$vocabulary->save();
}
//********** Translations. ***********//
// Load a term in multiple languages.
$en_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, 'en');
$fr_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, 'fr');
$de_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, 'de');
// Load a term for the current language.
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $language);
// Load for the current language
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties(['vid' => $taxonomy_name]);
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
foreach ($terms as $key => $term) {
$terms[$key] = \Drupal::service('entity.repository')->getTranslationFromContext($term, $language);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment