Autocomplete taxonomy with depth field
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:



 if ($entity-&gt;getEntityTypeId() == 'node') {
    if ($entity-&gt;bundle() == 'Machine_Name_content_type') {
    // Get the values from taxonomy term:
    $terms = $entity-&gt;get('field_tags')-&gt;getValue();
    if (!empty($terms)) {
        foreach($terms as $key =&gt; $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-&gt;parent = ['target_id' =&gt; $parent['target_id']];
                $term_loaded-&gt;save();
            }
        }

     }
  }
}


Hope to help you!