From 56eba8663c9a6b887f350b2c41e1fbac1cbb7e50 Mon Sep 17 00:00:00 2001 From: Arne De Meyer Date: Sun, 6 Oct 2024 10:46:55 +0200 Subject: [PATCH] Add: support for matrix & neo nested related elements --- src/RelatedElements.php | 29 ++++++++++++++++++++++++- src/templates/_element-sidebar.twig | 33 +++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/src/RelatedElements.php b/src/RelatedElements.php index e7fa300..e35cef6 100644 --- a/src/RelatedElements.php +++ b/src/RelatedElements.php @@ -9,6 +9,7 @@ use craft\elements\Category; use craft\elements\Entry; use craft\events\DefineHtmlEvent; +use craft\fields\Matrix; use yii\base\Event; /** @@ -35,7 +36,7 @@ private function attachEventHandlers(): void Event::on( Element::class, Element::EVENT_DEFINE_SIDEBAR_HTML, - static fn (DefineHtmlEvent $event) => $event->html .= + static fn(DefineHtmlEvent $event) => $event->html .= ($event->sender instanceof Entry || $event->sender instanceof Category || $event->sender instanceof Asset) @@ -53,7 +54,9 @@ public static function renderTemplate(Entry|Category|Asset $entry): string ]; $relatedElements = []; + $nestedRelatedElements = []; $hasResults = false; + $customFields = $entry->getFieldLayout()->getCustomFields(); foreach ($relatedTypes as $type => $class) { $relatedElements[$type] = $class::find()->relatedTo($entry)->status(null)->orderBy('title')->all(); @@ -62,11 +65,35 @@ public static function renderTemplate(Entry|Category|Asset $entry): string } } + foreach ($customFields as $field) { + $isMatrixField = $field instanceof Matrix; + $isNeoField = class_exists('\benf\neo\Field') && get_class($field) === \benf\neo\Field::class; + + if ($isMatrixField || $isNeoField) { + $blocks = $entry->getFieldValue($field->handle); + + foreach ($blocks->all() as $block) { + foreach ($relatedTypes as $type => $class) { + $nestedRelatedElements[$field->name][$type] = $class::find() + ->relatedTo($block) + ->status(null) + ->orderBy('title') + ->all(); + + if (!empty($nestedRelatedElements[$field->name][$type])) { + $hasResults = true; + } + } + } + } + } + return Craft::$app->getView()->renderTemplate( 'related-elements/_element-sidebar', [ 'hasResults' => $hasResults, 'relatedElements' => $relatedElements, + 'nestedRelatedElements' => $nestedRelatedElements, ] ); } diff --git a/src/templates/_element-sidebar.twig b/src/templates/_element-sidebar.twig index 20e186b..35e03b9 100644 --- a/src/templates/_element-sidebar.twig +++ b/src/templates/_element-sidebar.twig @@ -24,6 +24,39 @@ {% endfor %} {% endfor %} + {% for fieldKey, field in nestedRelatedElements %} +
+ + {{ fieldKey }} + +
+ {% for key, section in field %} + {% for element in section %} +
+ + +
+ {% endfor %} + {% endfor %} + {% endfor %} {% else %}

No related elements found.