Jump to content

$pages->find(selector) always return true


adrianmak
 Share

Recommended Posts

Here is a segment of code

$childpages = $pages->find("categories=500, sort=-post_date, limit=10");

if($childpages) 
    // do something if found
else // do something if not found

I found that the $page->find() always TRUE even though there is no page with field categories with value of 500

Link to comment
Share on other sites

Thats true... as it should. 

when using: if ($childpages) you ask: If PageArray... which is always true.

You should check if it contains pages with count for example.

if (!count($childpages)) {
    // The pageArray doesn't contain pages
    // If not count pages, thus 0
}

if (count($childpages)) {
    // yay we have at least 1 page 
}

// or
if ($childpages->count()) {
    // yay we have at least 1 page 
}
  • Like 5
Link to comment
Share on other sites

It seems that the count is not work for $page->next and $page->prev

Here is a cross reference post

https://processwire.com/talk/topic/11900-regarding-api-page-prev-and-page-next/?hl=prev

Using the count, always returned 0, no matter there is prev or next page is available.

i.e.

if (count($page->prev)) {    // this always 0 even though there is no prev page

}

Link to comment
Share on other sites

Next and prev return a single Page, not a PageArray, so you can’t count them. See the docs for $page->next: https://processwire.com/api/variables/page/ »This page's next sibling page, or NullPage if it is the last sibling.«

This is the same for all properties and methods that return only a single Page, like $pages->get(), $page->parent, $page->rootParent, etc. If nothing is found, they will give you a NullPage, which always has the id 0. So you can test for it using one of these conditions:

if ($page->next->id === 0) { /*$page is the last of its siblings*/ }

or

if ($page->next instanceof NullPage) { /*same here*/ }

Since 0 evaluates to false you can also go

if (!$page->next->id) { /*see above*/ }

if you’re into the whole brevity thing.

Sorry, can’t format on mobile.

  • Like 4
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...