Random loop info from child pages?

**Silverstripe Version: 3.4.0

Question:

Hi again, wondering if there is a way to display information from child pages (eg. title, snippet etc.) using a loop, but randomly sorting them on each page visit?

I’ve used the below code in my page controller:

function RandomChildren() { return $this->Children()->sort('RAND()'); }

Then called the loop like so in my page.ss template:

<% loop RandomChildren %>

Cheers

Hi,

what is the actual problem with your current solution?

Were you able to display info in your template, for example:

```
<% loop RandomChildren %>
    $Title
<% end_loop %>
```

Oh, I just noticed that you mentioned that you have defined your function in page controller. You should move it to your Page class. Or if you want to keep it in your controller class, change this…

function RandomChildren() { return $this->Children()->sort('RAND()'); }

to this:

function RandomChildren() { return $this->data()->Children()->sort('RAND()'); }

It looks to me like it should work too, and I don’t think you should need to add ->data() in there. You can probably also skip the controller method and do this in your template:

<% loop Children.Sort('RAND()') %>

That’s going to exclude you from being able to cache your output though, which is a performance loss. Wherever possible I think it’s best to do your randomisation client-side (just shuffle the order with a bit of javascript), so that you can cache the server side output.

Thanks heaps for your help @Taitava and @JonoM.

Neither of those options worked for me, however I think it maybe due to the crappy coding of the site (I’ve inherited the site from a previous designer).

However I did come across this snippet that worked a treat:

class ConsultationsPage_Controller extends Page_Controller {
	
	public function RandomChildren() {
		$random = DB::get_conn()->random();
		return ConsultationPage::get()->sort($random);
	}
	
}

Cheers guys

Ah interesting, I haven’t seen that before but that looks like the right way to do it! 'RAND()' always seemed hacky to me. Just curious - are you using something other than MySQL for your database? Maybe that’s why it didn’t work.