0

I am looking to achieve the next functionality:

I have a content type about fruits, I've added an autocomplete taxonomy field to the content type with the possibility to register new taxonomy.

I would like to achieve some taxonomy depth.

I am using the autocomplete deluxe module

For example, I input in the field apple, fresh, and green.

screenshot

When I go to the fruits taxonomy vocabulary, I would like to have the taxonomy depth like this.

screenshot

Instead, I get the following.

screenshot

Is there a way to achieve this with taxonomy autocomplete field?

1

I suggest implementing hook_entity_presave() getting values from taxonomy term reference field. If always the pre-term will be the parent of the current term then loop through the results of the term ids:

enter image description here

 if ($entity->getEntityTypeId() == 'node') {
    if ($entity->bundle() == 'Machine_Name_content_type') {
    // Get the values from taxonomy term:
    $terms = $entity->get('field_tags')->getValue();
    if (!empty($terms)) {
        foreach($terms as $key => $value) {
            // Exclude the first term because this will be the parent.
            if ($key != '0') {
                // Get the parent of the element.
                $parent = $terms[$key -1];
                // Load the current term.
                $term_loaded= \Drupal\taxonomy\Entity\Term::load($value['target_id']);
                // Set the parent: the term before.
                $term_loaded->parent = ['target_id' => $parent['target_id']];
                $term_loaded->save();
            }
        }

     }
  }
}

Hope to help you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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