I’ve uploaded 10 images to a files field on the panel that I want to use as a preloader image before the website pulls up. I want to randomize which one appears. Would there be a way to only grab one from the 10 images? Or would this be more achievable via javascript?
You can chain shuffle and first onto your images loop.
No, that’s possible:
$randomFile = $page->filesfieldname()->toFiles()->shuffle()->first();
Please always choose the question category the corresponds to your Kirby version. Thanks.
Ah okay, so It’s actually a little more complex. I’ve got an image and then an color overlay I want to go onto it that will then fade away, each image has a unique overlay like so:
I have two file fields, one for the image and one for the overlay. Would it be possible with Kirby methods to get both the image from one field and it’s appropriate overlay?
Edit: Categorized Properly. Thanks
Why don’t you store the overlay in the meta data instead of in separate files field?
But yes, if the order is the same, you can get the index of the file in the collection before shuffling and then get the corresponding index from the other field.
I didn’t know something like that was possible. Would it involve creating a file blueprint?
Yes. Define a files field in the files blueprint (use a query to limit the selection to overlays).
You can then fetch the overlay like this:
$overlay = $randomFile->overlayfield()->toFile();
Code of second option:
$files = $page->filesfieldname()->toFiles();
$randomFile = $files->shuffle()->first();
$index = $files->indexOf($randomFile);
$overlayForRandom = $page->overlayfield()->toFiles()->nth($index):
That works. Thank you!
I’d prefer the option with assigning the overlay in the metadata, but from a workflow point of view, the two files fields might be easier to handle for editors and if you put them side by side you get a more visual impression.