Have tried running this in an update hook, as well as via /devel/php, in both cases it failed.

Essentially, the taxonomy_term_save() function creates a term (as the name suggests) in the specified vocabulary. The vocabulary is supposed to optionally take the vocabulary ID or the vocabulary machine name. However, it currently only appears to work with the ID.

// this successfully inserts the term, but into a non-existent vocabulary with VID 0.
$res = taxonomy_term_save((object)array('name' => "Test Tag", 'vocabulary_machine_name' => "tags" )); 

// this successfully inserts the term, into the Tags vocabulary as expected.
$res = taxonomy_term_save((object)array('name' => "Test Tag", 'vid' => "1" )); 

The attached patch attempts to solve this. Note: regrettably I'm not a regular bug fixer/drupal core contributor, so this may be better solved in one of those presave invokes or something.

CommentFileSizeAuthor
#1 taxonomy_save_term-1896286-1.patch635 bytesalexkb
Support from Acquia helps fund testing for Drupal Acquia logo

Comments

alexkb’s picture

pcambra’s picture

Issue summary: View changes

According to the documentation in https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/funct...

vocabulary_machine_name: (optional) The machine name of the vocabulary the term is assigned to. If not given, this value will be set automatically by loading the vocabulary based on $term->vid.

Seems that the patch adds an expected behavior that if vocabulary_machine_name is provided, but not tid, it will load it from there.

I think it's a good addition but not sure if it would make sense to add it to Drupal 7 at this point...

alexkb’s picture

Good to finally see some interest in this after a year ;)

I think it's a good addition but not sure if it would make sense to add it to Drupal 7 at this point...

As no one else has replied over this time, it's probably not too important. Up to the powers at be, I guess.

mstef’s picture

I think it should be added. It just caused me to waste a good amount of time wondering why my terms were not showing up. This also can result in terms being stored in the database with a vid of 0, which means they remain hidden forever..

If you also look at:

if (!isset($term->vocabulary_machine_name)) {
    $vocabulary = taxonomy_vocabulary_load($term->vid);
    $term->vocabulary_machine_name = $vocabulary->machine_name;
  }

There is no check to make sure that $vocabulary is actually loaded before using it and proceeding.. (slightly different issue)

dcam’s picture

Status: Needs review » Closed (works as designed)

This is working as designed. "The vocabulary is supposed to optionally take the vocabulary ID or the vocabulary machine name" is an incorrect statement. The documentation doesn't say that the vid is optional. Only the vocabulary_machine_name is optional. Providing the machine name just allows you to skip a second taxonomy_vocabulary_load() and database query if you've already loaded it once.