Can’t get random values from array of structured fields …

I’m trying to get values from fields, but randomly only one instead of for each.

for each is working like this:

<?php foreach(page("testimonials")->testimonials()->toStructure() as $testimonial): ?>
        <?php echo $testimonial->text() ?>
<?php endforeach ?>

But I don’t get it randomly working. I tried a lot of variations of the below, with and without yaml(), with and without toStructure(), but unfortunately …

<?php $testimonials = page("testimonials")->testimonials()->yaml(); ?>
<?php $index = rand(0, sizeof($testimonials - 1); ?>

<?php //$testimonial = $testimonials[$index]; ?>
<?php //echo $testimonial->text() ?>

<?php echo $testimonials[$index]->text() ?>

Here’s my blueprint:

fields:
  title:
    label: Title
    type: text

  testimonials:
    label: Testimonials
    type: structure
    fields:
      name:
        label: Name
        type: text
      text:  
        label: Text 
        type: textarea  
        buttons: false
      [… other fields …]

Thank you very much for your great help on my project! : )

Try this …

<?php echo page("testimonials")->testimonials()->toStructure()->shuffle()->first() ?>
2 Likes

Now that’s some clever thinking. Thank you very much, @flokosiol

1 Like

… it’s a clever CMS. And that’s why I like it. :heart:

2 Likes

Note that if you have caching enabled, the first page generation will give you a random result, but subsequent visits will see the same cached result.

You can tell Kirby to ignore the cache for some pages:
https://getkirby.com/docs/developer-guide/advanced/caching#ignoring-pages