Skip to content

Commit

Permalink
Fix ForeignFieldModel::getRoot, it returns the canonical elements for…
Browse files Browse the repository at this point in the history
… matrix blocks
  • Loading branch information
sebastian-lenz committed Nov 29, 2023
1 parent 1c22cff commit 3abd09b
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions src/foreignField/ForeignFieldModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public function getRoot(): ElementInterface|null {
if ($this->_root === false) {
$this->_root = is_null($this->_owner)
? null
: $this->getParentElement($this->_owner);
: self::toParentElement($this->_owner);
}

return $this->_root;
Expand Down Expand Up @@ -166,16 +166,44 @@ protected function translate(string $message): string {
* @return ElementInterface
* @throws InvalidConfigException
*/
private function getParentElement(ElementInterface $element): ElementInterface {
private static function toParentElement(ElementInterface $element): ElementInterface {
if ($element instanceof MatrixBlock) {
return $this->getParentElement($element->getOwner());
return self::toParentElement(self::toMatrixParentElement($element));
}

if (is_a($element, 'verbb\supertable\elements\SuperTableBlockElement')) {
/** @noinspection PhpPossiblePolymorphicInvocationInspection */
return $this->getParentElement($element->getOwner());
return self::toParentElement($element->getOwner());
}

return $element;
}

/**
* @param MatrixBlock $element
* @return ElementInterface
* @throws Exception
*/
private static function toMatrixParentElement(MatrixBlock $element): ElementInterface {
try {
$owner = $element->getOwner();
if ($owner->id == $element->primaryOwnerId) {
return $owner;
}
} catch (\Throwable) {
// If the owner is trashed, we'll get an exception here. Ignore it and try fetching the element.
}

$sites = [$element->siteId, '*'];
$elements = Craft::$app->getElements();

while (count($sites)) {
$owner = $elements->getElementById($element->primaryOwnerId, null, array_shift($sites), ['trashed' => null]);
if ($owner) {
return $owner;
}
}

throw new Exception("Invalid parent id $element->primaryOwnerId for matrix block with id $element->id in site $element->siteId.");
}
}

0 comments on commit 3abd09b

Please sign in to comment.