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

Get Random Image


Go to End


14 Posts   5611 Views

Avatar
copernican

Community Member, 189 Posts

1 November 2012 at 5:57am

You don't need to extend the Page_Controller. Just put it in your SiteConfigCustom class

class SiteConfigCustom extends DataExtension {

public function getRandomImage() {
      return $this->BackgroundImages()->sort('RAND()')->First();
} 

}

and as far as i know, in your template file (Page.ss) you have to put the $ sign when using <% loop %>

<% loop $SiteConfig %>

<% end_loop %>

It may not work without the $.

Avatar
socks

Community Member, 191 Posts

1 November 2012 at 6:04am

If I put it up there, it breaks and I get the blank white page of death.

I don't believe the $ is necessary unless your doing something like <% if $MyDinner="kipper" %>

Avatar
copernican

Community Member, 189 Posts

1 November 2012 at 6:17am

oh, made a silly mistake...it should be

public function getRandomImage() {
    return $this->owner->BackgroundImages()->sort('RAND()')->First();
} 

need the "owner" part when your in a DataExtension :). I think that might fix it.

Avatar
socks

Community Member, 191 Posts

1 November 2012 at 6:30am

That seems to work with this change to the template:

Page.ss

<% loop SiteConfig %> 
	$RandomImage.BackgroundImage
<% end_loop %> 

Thanks to all!

Avatar
copernican

Community Member, 189 Posts

1 November 2012 at 6:34am

oh that's right. Good call on the template.

you could also use

<% loop SiteConfig.RandomImage %>
    $BackgroundImage
<% end_loop %>

if you wanted to loop through more then one random image.

Avatar
socks

Community Member, 191 Posts

1 November 2012 at 6:38am

Ok cool, thanks again!

Go to Top