Skip to content

Commit a1109fe

Browse files
martinyderimi-itk
authored andcommitted
Updated helper after code review
1 parent c812276 commit a1109fe

1 file changed

Lines changed: 14 additions & 10 deletions

File tree

web/modules/custom/hoeringsportal_project/src/Helper/ProjectHelper.php

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Drupal\hoeringsportal_project\Helper;
44

5+
use Drupal\Core\Cache\Cache;
56
use Drupal\Core\Datetime\DrupalDateTime;
67
use Drupal\Core\Entity\EntityInterface;
78
use Drupal\Core\Entity\EntityTypeManagerInterface;
@@ -113,24 +114,26 @@ public function projectFormAlter(array &$form, FormStateInterface $form_state):
113114
#[Hook('entity_presave')]
114115
public function entityPresave(EntityInterface $entity): void {
115116
if ($entity instanceof NodeInterface) {
117+
// When changing references, we must clear cache for nodes that was
118+
// previously referenced as well as new referenced nodes.
116119
try {
117120
if ($entity->hasField('field_project_reference')) {
118121
$newTargetId = (int) ($entity->get('field_project_reference')->target_id ?? 0);
119122

120123
$originalEntity = $entity->original ?? NULL;
121-
$oldTargetId = 0;
124+
$originalTargetId = 0;
122125
if ($originalEntity?->hasField('field_project_reference')) {
123-
$oldTargetId = (int) ($originalEntity->get('field_project_reference')->target_id ?? 0);
126+
$originalTargetId = (int) ($originalEntity->get('field_project_reference')->target_id ?? 0);
124127
}
125128

126129
// Only act if the reference actually changed.
127-
if ($oldTargetId === $newTargetId) {
130+
if ($originalTargetId === $newTargetId) {
128131
return;
129132
}
130133

131134
$idsToReset = [];
132-
if ($oldTargetId > 0) {
133-
$idsToReset[] = $oldTargetId;
135+
if ($originalTargetId > 0) {
136+
$idsToReset[] = $originalTargetId;
134137
}
135138
if ($newTargetId > 0) {
136139
$idsToReset[] = $newTargetId;
@@ -140,18 +143,19 @@ public function entityPresave(EntityInterface $entity): void {
140143
return;
141144
}
142145

146+
// Clear cache for project nodes when we change an entity pointing to
147+
// it.
143148
$idsToReset = array_values(array_unique($idsToReset));
144-
$this->entityTypeManagerInterface->getStorage('node')
145-
->resetCache($idsToReset);
149+
$nodes = $this->entityTypeManagerInterface->getStorage('node')->load($idsToReset);
150+
foreach ($nodes as $node) {
151+
Cache::invalidateTags($node->getCacheTags());
152+
}
146153
}
147154
}
148155
catch (\Exception $e) {
149156
$this->logger->error('Error in node presave hook: @message', ['@message' => $e->getMessage()]);
150157
}
151158

152-
$this->entityTypeManagerInterface->getStorage('node')
153-
->resetCache([$entity->id()]);
154-
155159
// Delete orphaned paragraphs when references are removed.
156160
$this->deleteOrphanedParagraphs($entity);
157161
}

0 commit comments

Comments
 (0)