0

I have added a field to the Tags vocabulary, Count.

In my Tags taxonomy term entity bundle, I run a database query in preSave() to set the value of this field (how many nodes have an entity reference to this term).

To keep the Tags term counts up to date, when a node with a Tags entity reference field is saved, in postSave() on my node bundle, I resave the Tags term:

  public function postSave(EntityStorageInterface $storage, $update = TRUE): int {
    $tag_id = (int) $this->field_tags->target_id;
    if ($tag_id > 0) {
      $term = $this->entityTypeManager()->getStorage('taxonomy_term')->load($tag_id);
      $term->save();
    }
    parent::postSave($storage, $update);
    return 1;
  }

This is fine when adding tags.

However, when removing tags, then the term for the removed tag is not resaved, so the count is incorrect.

I tried to fix this in the node entity bundle's preSave():

if (!$this->isNew()) {
  $tag_id = (int) $this->field_tags->target_id;
  $original_node = $this->original;
  $original_tag_id = (int) $original_node->field_tags->target_id;
    // If ID of group has changed or been removed, we also need to resave the original.
    if ($original_tag_id > 0 && ($original_tag_id !== $tag_id)) {
      $term = $this->entityTypeManager()->getStorage('taxonomy_term')->load($original_tag_id);
      $term->save();
    }
  }
}

While this code re-saves the term that is resaved, because this is run in preSave(), it runs before the node is updated, so the count is off by one because the node has not been updated (to remove the tag) yet.

So I'm stuck-- to get the original node to detect if a tag is removed, I need to be in preSave, but to resave the tag, I need to do so in postSave.

Is there some way I can trigger a re-save of an entity after editing another entity, but only after the edited entity has been saved?

3
  • Are you sure you don't have access to $this->original in postSave()?
    – 4uk4
    Aug 24, 2022 at 7:28
  • @4uk4 Yes, when I try the preSave() code above in postSave(), I get Warning: Attempt to read property "field_tags" on null in Drupal\MyModule\Bundle\NodeBundle->postSave() . Aug 24, 2022 at 7:39
  • The problem could be the condition isNew() because when a new entity is saved it is no longer new, but $this->original should work, if it s not a new entity, just tested it in my IDE.
    – 4uk4
    Aug 24, 2022 at 8:36

1 Answer 1

1

In a postSave event you can no longer test isNew(). So check for the original entity instead, which is only present if the save operation is updating and not creating an entity:

if (isset($this->original)) {
  $original_node = $this->original;

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.