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?
preSave()
code above inpostSave()
, I getWarning: Attempt to read property "field_tags" on null in Drupal\MyModule\Bundle\NodeBundle->postSave()
.