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.

General Questions

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

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

Getting random dataobjects


2 Posts   2309 Views


4 May 2011 at 8:24am Community Member, 41 Posts

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? :)


10 May 2011 at 3:26am (Last edited: 10 May 2011 3:29am), Community Member, 41 Posts

---- 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. [url][/url]

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 {