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

Getting random dataobjects


Go to End


2 Posts   5020 Views

Avatar
ayyurek

Community Member, 41 Posts

4 May 2011 at 8:24am

Hello,
I have ProductPages which has many ProductImages.

I can get 3 random Product Page with the following code

function RandomProductPages($num=3) {
	return DataObject::get("ProductPage", "", "RAND()", "", $num);
    }

I can also get random ProductImages with the following code :)

function RandomProductImage($num=1) {
	return DataObject::get("ProductImage", "", "RAND()", "", $num);
    }

How to combine them, so that I can get 3 random product pages with 1 random image for each? :)

Avatar
ayyurek

Community Member, 41 Posts

10 May 2011 at 3:26am

Edited: 10/05/2011 3:29am

---- SOLVED ----

Ok, in the end I solved it. I post the code below, for future visitors :) The main product image is selected randomly from child images. You can use it for custom galleries. The key point is, this function must be created in the subclass, not in the controller. Thanks to edk for this great tip. http://silverstripe.org/general-questions/show/15631?start=8#post302895#post302895


class ProductPage extends Page {
		static $db = array(
	);

   function CoverImage($num = 1) { 
   $Data = $this->getComponents('Photos', '', 'RAND()', '', $num);
   return $Data; 
}

}

class ProductPage_Controller extends Page_Controller {
 
}