Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Template Questions /

Getting Random Children


Reply


2 Posts   716 Views

Avatar
nitromike

Community Member, 3 Posts

19 July 2012 at 9:22am

I'm trying to retrieve random children of a product group page. I can retrieve the product group page from teh template, but I can't call any more custom functions. currently in my Page.php I'm using

function RandomChildren($count = 2)
{
$pages = DataObject::get("SiteTree","ParentID = $this->ID","RAND()",null,$count);
Debug::show($pages);
return $pages;

}

And to call in the template I'm using

<% control RandomChildren(2) %>
...
<% end_control %>

But the Debug isn't even showing, and I'm in "Dev" mode

I've tried other methods, and also found that at one point, if I retrieve a page using

return DataObject::get('SiteTree','ParentID = $this->ID);


I will debug and see the results of the object as expected,

but when I use this to get random children it fails, if i debug the ID of the object, it's empty

$page = DataObject::get('SiteTree','ParentID = $this->ID)
Debug::show($page->ID);

This site is very complicated, but the logistics should work. I've used this code before on other projects, and have never seen this problem, any thoughts anyone???

Avatar
gaethofs

Community Member, 9 Posts

4 November 2012 at 3:36am

Edited: 04/11/2012 3:38am

What version of SS are your using?

You could do something like this:

function RandomChildren($count = 2) {
   return SiteTree::get()->filter('ParentID', $this->ID)->sort('RAND()')->limit($count);
}

I gave this a quick try and it works fine. Hope this works for you!