Jump to content

Recommended Posts

Posted

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?

Posted

Hi @Tyssen.

for($i = 0; $i < 5; $i++):
$randomPage = $pages->find("your selector here")->findRandom(1);
foreach($randomPage->repeater_field->getRandom(3) as $item) :
				Output
		endforeach;
endfor;

Hope this helps.

  • Like 1
Posted

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

 

Posted

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.

Posted

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
Posted

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
Posted

Thanks guys, I think I have it working, but I'm waiting for feedback from the content editor because I'm unsure if the output is as expected.

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
  • Recently Browsing   0 members

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