Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Random Images from Gallery Albums


Go to End


4 Posts   1197 Views

Avatar
SS SS

Community Member, 24 Posts

16 March 2012 at 1:37am

Edited: 16/03/2012 1:39am

Hi,

I am using the following code to fetch 6 random images from all the albums located in one gallery, but sometimes I am getting 3 random images, sometimes 4 and soon. It is not always 6 random images.

What I am doing wrong?

function GalleryImages() {
$gallery = DataObject::get_one("ImageGalleryPage");
$items = DataObject::get("ImageGalleryItem","ImageGalleryPageID = {$gallery->ID}","RAND()",null,6);
return $gallery->GalleryItems(null,$items);
}

Avatar
SS SS

Community Member, 24 Posts

17 March 2012 at 12:33am

Anybody please???

Avatar
Nobrainer Web

Community Member, 138 Posts

19 March 2012 at 9:01am

Why are you doing return $gallery->GalleryItems(null,$items);
and not just: return $items;

Sorry if it's not a help, i just got curious :o)

Avatar
novaweb

Community Member, 116 Posts

19 March 2012 at 9:54am

ss-ss,

This is probably because RAND() is returning numbers outside of the range in which gallery items exist within your gallery.

I would run:

$items = DataObject::get("ImageGalleryItem","ImageGalleryPageID = {$gallery->ID}");

To return all of your images, first.

Then put the id's of the $items in to an array.

Then use shuffle on the array ( http://nz.php.net/shuffle )

Then inside a for loop (limited to 6), run DataObject::get_by_id inside the loop using the shuffled id's, append each result to a new DataObjectSet thenm return that at the end of your function.

Good luck!