Skip to content

Instantly share code, notes, and snippets.

@elistone
Created January 28, 2020 13:39
Show Gist options
  • Save elistone/bbad0097d811aea51cb3f678f0361dc4 to your computer and use it in GitHub Desktop.
Save elistone/bbad0097d811aea51cb3f678f0361dc4 to your computer and use it in GitHub Desktop.
Drupal 8 - Find or Create Taxonomy Trait
<?php
namespace Drupal\MY_MODULE_NAME;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\taxonomy\Entity\Term;
trait FindOrCreateTaxonomyTrait {
/**
* Find or create a new taxonomy
*
* @param null $name
* @param null $vid
*
* @return int
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function findOrCreateTaxonomy($name = NULL, $vid = NULL) {
// Truncate to 255 characters, this is taxonomy term name limit
$name = substr($name, 0, 255);
// look up the term
$find = self::getTidByName($name, $vid);
// can find a term return the tid
if ($find > 0) {
return $find;
}
// otherwise create a new term
return self::createTerm($name, $vid);
}
/**
* Utility: find term by name and vid.
*
* @param null $name - Term name
* @param null $vid - Term vid
*
* @return int - Term id or 0 if none.
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function getTidByName($name = NULL, $vid = NULL) {
$properties = [];
if (!empty($name)) {
$properties['name'] = $name;
}
if (!empty($vid)) {
$properties['vid'] = $vid;
}
$terms = \Drupal::entityManager()
->getStorage('taxonomy_term')
->loadByProperties($properties);
$term = reset($terms);
return !empty($term) ? $term->id() : 0;
}
/**
* @param null $name
* @param null $vid
*
* @return int
*/
public function createTerm($name = NULL, $vid = NULL) {
try {
$term = Term::create([
'name' => $name,
'vid' => $vid,
])->save();
return $term;
} catch (EntityStorageException $e) {
die($e->getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment