42

I'm attempting to add a lot of terms (~200) to a vocabulary, but I can't find any import modules that are updated for Drupal 8, and it seems the functions for doing this in Drupal 7 don't exist in Drupal 8. So, can anyone point me in the right direction for doing this?

I attempted to do it with entity_create, as suggested in the comments, with this code:

$term_create = entity_create('taxonomy_term', array('name' => 'test', 'vocabulary_name' => 'client'));

but I got this error:

Drupal\Core\Entity\EntityStorageException: Missing bundle for entity type taxonomy_term in Drupal\Core\Entity\FieldableEntityStorageControllerBase->create() (line 65 of core/lib/Drupal/Core/Entity/FieldableEntityStorageControllerBase.php).

Any ideas?

4
  • 1
    A term is an entity, so...entity_create()
    – Clive
    Apr 2, 2014 at 16:40
  • I attempted to do this with this code: $term_create = entity_create('taxonomy_term', array('name' => 'test', 'vocabulary_name' => 'client'));, but I got the error Drupal\Core\Entity\EntityStorageException: Missing bundle for entity type taxonomy_term in Drupal\Core\Entity\FieldableEntityStorageControllerBase->create() (line 65 of core/lib/Drupal/Core/Entity/FieldableEntityStorageControllerBase.php). -- Any ideas?
    – Samsquanch
    Apr 2, 2014 at 17:20
  • Try vid in place of vocabulary_name. Looks like the column is still vid in taxonomy_term_data, but it's the vocab name instead of id now
    – Clive
    Apr 2, 2014 at 17:26
  • The entity data should not be derived from the SQL tables, see below.
    – user49
    Apr 2, 2014 at 17:37

6 Answers 6

55

You know that you want something from taxonomy module so first you need to look in Drupal\taxonomy\Entity -- or the corresponding directory -- you will find the Term class there. Now look at the annotation, it says @ContentEntityType and in there:

*   entity_keys = {
*     "id" = "tid",
*     "bundle" = "vid",
*     "label" = "name",
*     "uuid" = "uuid"
*   },

So, what you want is

$term = Term::create([
  'name' => 'test', 
  'vid' => 'client',
])->save();

because the label entity key is name and the bundle entity key is vid. I added a ->save() call as well as I presume you wanted to save it too.

3
  • More options are available over at drupal8.ovh/en/tutoriels/55/….
    – colan
    Jun 2, 2016 at 15:41
  • 2
    $term = \Drupal\taxonomy\Entity\Term::create(array( 'name' => 'whatever', 'vid' => 'tags', )); $term->save(); gives me Fatal error: Call to undefined method Drupal\taxonomy\Entity\Term::getType
    – alberto56
    Jun 6, 2016 at 18:58
  • yes, it's working well..
    – sekharctc
    Jun 12, 2020 at 9:51
15

At this time you should add term in little bit another way (in compare with this answer) First of all in your file begin you should write

use Drupal\taxonomy\Entity\Term;

Because Term class listed in Drupal\taxonomy\Entity. And you don't need to pass taxonomy_term parametr to

Term::create

because only one parametr is needed (array with values) (below listed code for this method in taxonomy module)

public function create(array $values = array()) {
  // Save new terms with no parents by default.
  if (empty($values['parent'])) {
    $values['parent'] = array(0);
  }
  $entity = parent::create($values);
  return $entity;
}

So the final example is

use Drupal\taxonomy\Entity\Term;
$categories_vocabulary = 'blog_categories'; // Vocabulary machine name
$categories = ['test 1', 'test 2', 'test 3', 'test 4']; // List of test terms
foreach ($categories as $category) {
  $term = Term::create(array(
    'parent' => array(),
    'name' => $category,
    'vid' => $categories_vocabulary,
  ))->save();
}
1
  • 5
    Something you may want to know. $term will be equal to 1 most likely because Entity::save() returns an int. Either the constants SAVED_NEW or SAVED_UPDATED depending on the operation performed. However, if you were to remove the ->save() and add $term->save();, you will then see that $term is updated with the information that was saved to the database. Example you can now do $tid = $term->tid->value; Jan 23, 2016 at 2:22
9

With entityTypeManager():

$term = [
  'name'     => $name,
  'vid'      => $vocabulary,
  'langcode' => $language,
];

$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->create($term);
2
  • save() doesn't return the entity object, so $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->create($term)->save(); is wrong, as it would store in $term an integer, not an entity object.
    – apaderno
    Jun 12, 2020 at 9:33
  • 2
    \Drupal::entityTypeManager()->getStorage('taxonomy_term')->create($term)->save()' will return the status (an integer indeed 0 or 1) but it works for saving the term. If you wish to use the term as well, you need to create() first (returns the term entity) and then $term->save()
    – misterdidi
    Jul 3, 2020 at 13:33
8
Term::create([
 'name' => 'Lama',
 'vid' => $vocabulary_id,
]);

The other answers use entity_create(), which works, but is not quite as nice as the OOP approach.

0
7

Before creating a term, it's better to check if it's exist, here is the code:

use Drupal\taxonomy\Entity\Term;

if ($terms = taxonomy_term_load_multiple_by_name($term_value, 'vocabulary')) {
  // Only use the first term returned; there should only be one anyways if we do this right.
  $term = reset($terms);
} else {
  $term = Term::create([
    'name' => $term_value,
    'vid' => 'vocabulary',
  ]);
  $term->save();
}
$tid = $term->id();

Source: https://www.btmash.com/article/2016-04-26/saving-and-retrieving-taxonomy-terms-programmatically-drupal-8

2

You may want to look at how devel/devel_generate does this.

From devel_generate :

$values['name'] = devel_generate_word(mt_rand(2, $maxlength));
$values['description'] = "description of " . $values['name'];
$values['format'] = filter_fallback_format();
$values['weight'] = mt_rand(0, 10);
$values['langcode'] = LANGUAGE_NOT_SPECIFIED;
$term = entity_create('taxonomy_term', $values);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.