Hello,
Recently I ran into some weird behavior with the find() method, when using it within the context of a single $page.
Although this is easy (and perhaps more correct) to work around using the get(), child() or children() methods, I'd still like to understand what is happening here.
This is an example of a piece of code, where $page is trying to get its child with a specific template, using the find() method, but returns nothing instead.
<?php
// Prepare PW
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['HTTP_HOST'] = 'localhost';
$_SERVER['REQUEST_URI'] = '/index.php';
// get Wire'd
require_once dirname(__FILE__).'/../../www_composer/index.php';
// get some entries where the template failed to laod
$data = file_get_contents('failed_entries.json');
$data = json_decode($data);
foreach ( $data as $row )
{
$entry = wire('pages')->get('template=offers-page, email='. $row->email);
echo sprintf("This page has the id %d, it contains meta-data for an email\n", $entry->id);
echo sprintf("\t- it has %d child (with ID %d), which is a template ('email-base'),\n",
$entry->numChildren(),
$entry->child()->id
);
echo sprintf("\t- the child (template) has %d children (which are blocks in the template),\n", $entry->child()->numChildren());
echo "We want to get the child that uses the 'email-base' template (because in theory there could be many children to this page)\n";
echo sprintf(
"\tWhy is find() returning '%s' when filtering with template name,\n",
($entry->find('template=email-base')->count()? $entry->find('template=email-base')->count(): 'NOTHING')
);
echo sprintf(
"\twhile get() returns the expected page with id: %d\n",
$entry->get('template=email-base')->id
);
echo "When further researching this, it would seem that using find on \$page, actually returns it\'s grandchildren\n";
$i=1;
foreach ( $entry->find() as $gc ) {
echo sprintf("\t- I'm a grandchild, and my parent is %d and not %d\n",
$gc->parent()->id,
$entry->id
);
$i++;
}
break;// casue we only need to look at one..
}
Even more interesting is that sometimes this $page->find('template=tpl-name')->first()->id returned an id, and sometimes it threw a notice.
The above code is a test CLI script, which produces weird results.
On the other hand when I tested using find() in a template, it worked while testing, but later our users reported an error that is caused by $page->find('template=tpl-name')->first()->id throwing a notice.
What is the behavior of find() supposed to be in this case?
Am I missing something?