Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SkyLundy/ee3b8157175a7cbdf59da232b3f72bd4 to your computer and use it in GitHub Desktop.
Save SkyLundy/ee3b8157175a7cbdf59da232b3f72bd4 to your computer and use it in GitHub Desktop.
Add a 'getMatrixChildren()' method to RepeaterMatrixPage objects
<?php
declare(strict_types=1);
namespace ProcessWire;
/**
* Custom method that gets nested child RepeaterMatrixPage objects as a PageArray for the
* RepeaterMatrixPage executed upon. This simulates accessing RepeaterMatrix items as pages
*
* Usage, can be used on any RepeaterMatrix page with nested children:
* $page->repeater_matrix_field->first()->getMatrixChildren(); // => PageArray
*/
$wire->addHookMethod('RepeaterMatrixPage::getMatrixChildren', function(HookEvent $e) {
$targetMatrixPage = $e->object;
$repeaterMatrixField = $targetMatrixPage->getForField()->name;
$targetMatrixPageMatched = false;
$targetMatrixPageChildren = [];
// Get field on page where the target matrix page exists
$targetMatrixField = $targetMatrixPage->getForPage()->$repeaterMatrixField;
foreach ($targetMatrixField as $repeaterMatrixPage) {
if ($repeaterMatrixPage->id === $targetMatrixPage->id) {
$targetMatrixPageMatched = true;
continue;
}
if (!$targetMatrixPageMatched) {
continue;
}
if ($repeaterMatrixPage->getDepth() === $targetMatrixPage->getDepth() + 1) {
$targetMatrixPageChildren[] = $repeaterMatrixPage;
continue;
}
// When the depth is at or below the target page depth, we've retrieved all of the children
if ($repeaterMatrixPage->getDepth() <= $targetMatrixPage->getDepth()) {
break;
}
}
$e->return = PageArray($targetMatrixPageChildren);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment