Jump to content

Get random items from repeater field from specific pages


Tyssen
 Share

Recommended Posts

I have a series of pages that use a repeater field and I want to fetch 3 random rows from each repeater from 5 specific pages, so that I'll have a total of 15 items output, but then also randomise the output so that items from the same repeater field aren't next to each other.

Originally I had 

$selected_pages = $pages->getById([1049,1053,1055,1059,1152]);
		foreach($selected_pages as $selected_page) :
			foreach($selected_page->repeater_field->getRandom(3) as $item) :
				Output
		endforeach;
endforeach;

That gave me the pages randomised, but also gave me the items from each page's repeater next to each other.

So then I tried

$selected_pages = $pages->get("id=1049|1053|1055|1059|1152")->repeater_field->find("limit=15, sort=random");

but that's just randomly pulling 15 items from the first page, the one with id 1049.

How do I go about randomising both the pages and the repeater items as well?

Link to comment
Share on other sites

With

$randomPage = $pages->get("id=1049|1053|1055|1059|1152")->findRandom(1);

or getRandom(1) I get

Quote

Error: Exception: Method Page::findRandom does not exist or is not callable in this context

 

Link to comment
Share on other sites

I then get an error on the next line.

Quote

Call to a member function getRandom() on null

And in testing whether $randomPage was actually returning anything by just outputting the page title, I'm getting

Quote

Page A
Page A
Page B
Page C
Page C

instead of repeater items randomised from Pages A–E.

Link to comment
Share on other sites

I got your idea wrong. Let me see....

$randomPages = $pages->find("your selector here")->shuffle();
foreach($randomPages as $randomPage):
foreach($randomPage->repeater_field->findRandom(3) as $item) :
				Output
		endforeach;
endforeach;

Use findRandom() instead of getRandom().

  • Like 1
Link to comment
Share on other sites

Try:

$result = new PageArray();
foreach($pages->getById([1049,1053,1055,1059,1152]) as $p) {
    $result->add($p->repeater_field->findRandom(3));
}
$result->shuffle();
// Now do something with $result - foreach, etc.

 

  • Like 1
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...