0

I'm looking to add a taxonomy term to a vocabulary upon the creation of content type.

For example I have a taxonomy vocabulary called "Widget Type".

I have a content type of Product. When I create an instance of product I would like the title (product.title_1) to be added as a taxonomy term to Widget Type.

Then every time a new product is created a term is added. Widget Type would then contain the terms... title_1 title_2...etc.

Does this require a custom module or is there an easier way to do this that I'm not aware of?

Thanks

2
  • is there an easier way to do this probably with Rules.
    – No Sssweat
    Commented Aug 10, 2017 at 18:05
  • can you just add an entity reference field to that vocab with the option set to create the term if it doesn't exist? That requires no code or additional modules. You just have to input the title twice I suppose
    – Ronnie
    Commented Aug 30 at 16:58

1 Answer 1

0

You can trigger this behavior by implementing hook_entity_presave() in a custom module. Inside of this hook, you will call a function which creates each time the taxonomy term using the title of the node created.

test.module

use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_presave().
 */
function test_entity_presave(EntityInterface $entity) {
   if ($entity->bundle() == 'product') {
    if ($entity->isNew()) {
      $title = $entity->get('title')->getValue();
      \Drupal\test\Test::createTerm($title[0]['value']);
    }
  }
}

Assuming you have defined createTerm() in a Test class…

Test.php (in the src folder)

namespace Drupal\test;

/**
 * Test class.
 */
class Test {
  public static function createTerm($title) {
    $term = [
      'name'     => $title,
      'vid'      => 'widget_type',
      'langcode' => 'en',
    ];
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->create($term);
    $term->save();
  }
}

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.