Related pages: programmatical pages field from a pages query

I have this related publications section:

related_publications:
    label: Related Publications
    type: pages
    query: page('publications').children.listed

Editors can use it to manually link from one publication to related publications. I renders like this:

<?php if($page->related_publications()->isNotEmpty()): ?>
<div class="related">
	<h3 class="related-name">Publications</h3>
	<ul class="related-pages">
	<?php foreach($page->related_publications()->toPages() as $p): ?>
		<li class="related-pages-entry">
			<a class="related-pages-entry-link" href="<?= $p->url() ?>">
				<?= $p->title()->h() ?>
			</a>
		</li>
	<?php endforeach ?>
	</ul>
</div>
<?php endif ?>

Now there are also author pages. They, too, should show related publications. But that list should be created dynamically. Since I want to reuse the snippet I had to come up with a way to create the pages field via the author page model:

<?php

class TeamMemberPage extends Page {
	public function related_publications() {
		$pages = page('publications')->children()->listed()->filterBy('authors', '*=', $this->uuid())->sortBy('date', 'desc');
		$uuids = array_map(fn($p) => 'page://'.$p['content']['uuid'], $pages->toArray());

		return new Field(
			$this,
			'related_publications',
			Yaml::encode(array_values($uuids))
		);
	}
}

If there is a simpler way to dynamically create the field, I’m all ears.

Hm, I would create a model that returns related publications for both page types, then you don’t need this detour with the field.

So a method relatedPublications in the default page model that returns $this->related_publications()->toPages() and to overwrite it in the TeamMemberPage model, returning the queried pages? Sounds like a good idea. I’m not used to having a default page model :smile:

Exactly.