I have a node type 'blog_entry' that uses a taxonomy reference (tags). The tags are created if they don't already exist, i.e. the reference field uses the option 'Create referenced entities if they don't already exist'. My node bundle as well as the taxonmy term 'tags' have both a field 'field_section', which is also a taxonmy reference.

I would like to set the 'field_section' of the taxonomy 'tags' to the same value as the one 'field_section' on my 'blog_entry' node when I create a new node.

This means: when creating a ne blog_entry I'm selecting a value for the field_section and I'm entering a new value for the field_tags. The new taxonomy value is successfully created in 'tags' but I would also like to set it's field_section to the same value as choosen for the blog_entry.


thinking the fastest way to do this one is hook_node_insert() ... see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_insert/8.2.x

if i am following what your saying, you want to set the value of 'field_section' the newly created taxonomy term in tags? if so the following will get you started ..

 * Implements hook_ENTITY_TYPE_insert().
function YOURMODULE_node_insert(EntityInterface $entity) {
  $type = $entity->bundle();
  if (!empty($type) && $type == 'blog_entry') {
      $field_tags_terms = $entity->field_tags->referencedEntities();
      // Your selected term id.
      $field_section_id = $entity->field_section->target_id;
      if (!empty($field_tags_terms) && !empty($field_section_id)) {
          foreach ($field_tags_terms as $term) {
              $term->set('field_section', $field_section_id);
              // or 
              // $term->field_section->appendItem(['target_id' => $field_section_id]);
  • It works!.Previously I tried hook_entity_type_create and the following code. But it didn't work. Do you know why not? $site_section = $node->get('field_section'); $entity->get('field_tags')->referencedEntities()[0]->set('field_section', $site_section); – Bulgo Dec 13 '19 at 10:20
  • hook_entity_type_create is fired before the "add new" form even loads – Taggart Jensen Jan 2 at 22:21

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