To Term

I often need to create taxonomy terms, checking if they exist first. This is a small function that handles that.
<?php

use Drupal\taxonomy\Entity\Term;
use
Drupal\taxonomy\Entity\Vocabulary;

 
/**
   * Get term id, create if missing.
   *
   * @param string $name
   *   Term name.
   * @param string $vid
   *   Vocabulary id.
   * @param string $langcode
   *   Language code.
   *
   * @return int
   *   Term id.
   */
 
protected function toTerm($name, $vid, $langcode = 'zxx') {

   
// Force zxx if vocabulary is not translatable.
   
$vocab_langcode = Vocabulary::load($vid)->language()->getId();
    if (
$vocab_langcode === 'zxx') {
     
$langcode = 'zxx';
    }

   
// Get existing.
   
$name = trim($name);
   
$res = \Drupal::entityQuery('taxonomy_term')
      ->
condition('vid', $vid)
      ->
condition('name', $name)
      ->
condition('langcode', $langcode)
      ->
execute();
    if (!empty(
$res)) {
     
$tid = reset($res);
    }

   
// Create new.
   
else {
     
$term = Term::create([
       
'vid' => $vid,
       
'name' => $name,
       
'langcode' => $langcode,
      ]);
     
$term->save();
     
$tid = $term->id();
    }

    return
$tid;
  }

?>
Tags