diff --git a/CHANGELOG.md b/CHANGELOG.md index bfe8f061a47..1144ef1c479 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - Fixed an error that occurred when running the `entrify/global-set` command. ([#15746](https://github.com/craftcms/cms/issues/15746)) - Fixed a bug where users’ `username` values weren’t getting updated based on email address changes when `useEmailAsUsername` was enabled. ([#15758](https://github.com/craftcms/cms/issues/15758)) - Fixed a bug where the `hasAlt` asset query param wasn’t working properly. ([#15762](https://github.com/craftcms/cms/issues/15762)) +- Fixed a bug where relational fields could show related elements for other field instances within element indexes. ([#15777](https://github.com/craftcms/cms/issues/15777)) ## 5.4.4 - 2024-09-14 diff --git a/src/fields/BaseRelationField.php b/src/fields/BaseRelationField.php index 6b1c4ae2d80..52b4322da24 100644 --- a/src/fields/BaseRelationField.php +++ b/src/fields/BaseRelationField.php @@ -927,6 +927,13 @@ public function getPreviewHtml(mixed $value, ElementInterface $element): string /** @var ElementQueryInterface|ElementCollection $value */ if ($value instanceof ElementQueryInterface) { $value = $this->_all($value, $element)->collect(); + } else { + // todo: come up with a way to get the normalized field value ignoring the eager-loaded value + $rawValue = $element->getBehavior('customFields')->{$this->handle} ?? null; + if (is_array($rawValue)) { + $ids = array_flip($rawValue); + $value = $value->filter(fn(ElementInterface $element) => isset($ids[$element->id])); + } } return $this->previewHtml($value);