Why does this page method fail when $this is draft?

I have a custom page method that finds all ‘show’ pages that reference $this in their ‘worksincluded’ field:

<?php
Kirby::plugin('jaume/page-methods', [
	'pageMethods' => [
		'includedInShows' => function () {
			return page("shows")->childrenAndDrafts()->filter(function ($show) {
				return $show->worksIncluded()->toPages()->has($this);
			});	
		},
	]
]);

And I use it in a pagesdisplay field as such:

shows:
  label: Shows 
  type: pagesdisplay
  query: page.includedInShows

This works well UNLESS $this page is a draft, in which case it fails i.e. the pagesdisplay field shows nothing.

Why would this be ?

Initially I though that the ‘worksincluded’ field at the ‘show’ pages did not include the ‘show’ pages when they were draft, and thus the ‘incudedInShows’ did not find them. But I believe that should not be the case because I use ‘childrenAndDrafts’ in ‘worksincluded’ as such:

worksIncluded:
  label: Works Included
  type: pages
  query: kirby.page("works").childrenAndDrafts.notTemplate("gap")

So what is going on ? Something simple I can’t see?

Thank you

Because toPages() doesn’t include drafts.

Is there a ready-to-use alternative ?

Thank you

Ah, this happened before

I am going to see if a custom method is within my abilities.

Thanks

@texnixe I am trying to adapt an example workaround you give in another, similar, post, that goes like this:

$selectedPages = $page->pagesfield()->yaml();
foreach ($selectedPages as $selectedPage) {
  dump(page($selectedPage));
}

but page() does not return drafts, reference says we have to use $kirby->page(). But how do I use $kirby or kirby() in a field method ?

Thanks

You can always use the kirby() helper:

kirby()->page('somepage')

Ah yes, for some reason that did not work the first time around.

So, a toPagesAndDrafts custom method could be something like:

<?php
Kirby::plugin('jaume/field-methods', [
    'fieldMethods' => [
        'toPagesAndDrafts' => function ($field) {
            $selectedPages = $field->yaml();
            $result = new Pages();
            foreach ($selectedPages as $page) {
                $result->add(kirby()->page($page));
            }
            return $result;
        },
    ]
]);