Ok. After banging my head on the desk a few times trying to figure out the syntax (I'm a noob with the Silverstripe framework) here's my solution:
Case: This shows 2 header images which are added to the Page PageType. If they're not available on the current page, we'll search through all the parents to find some.
In Page.php
class Page extends SiteTree {...
static $has_one = array(
'HeaderImage1' => 'Page_Image',
'HeaderImage2' => 'Page_Image',
);
... }
Notice the reference to the extended Page_Image class, and not the Image class (see Page_Image class below).
In the Controller class we need to grab the header image, if we have one. If we don't have one, then we'll call a recursive function which loops through parents, and parents of parents, etc untill we find a header image we can use. The whole $Number thing is simply because we had 2 headerimages in this particular case and wanted a generic function.
class Page_Controller extends ContentController {...
function grabHeaderImage($Number) {
$HeaderImage = $this->getComponent('HeaderImage'.$Number);
if(!empty($HeaderImage->ID)){
$HeaderImage = $HeaderImage->Thumbnail();// see the Page_Image class below to see what ->Thumbnail() does
} else {
$HeaderImage = $this->getParentHeaderImage($this, "HeaderImage".$Number);
$HeaderImage = $HeaderImage->Thumbnail();
}
return $HeaderImage;
}
/* This is a recursive funtion used in grabHeaderImage: It requests the HeaderImage1 of the parent
If it's found, it's returned. If it's not found, it calls itsself again */
private function getParentHeaderImage($CurrentPage, $HeaderNumber){
$Parent = $CurrentPage->Parent;
if(is_object($Parent)){
$HeaderImage1 = $Parent->getComponent($HeaderNumber);
if(!empty($HeaderImage1->ID)){
return $HeaderImage1;
// We found the current header! Let's return it!
} else {
return $this->getParentHeaderImage($Parent, $HeaderNumber);
// We didn't find a header,so we have to call ourselves again
}
} else {
return false;
}
}
...}
At the end of the Page.php (after we extend the controller) we want to work some magic on the image with resizing,etc.
class Page_Image extends Image {...
// define different GD functions to resize uploaded photos, see the GD page in the
// SilverStripe documentation for different functions for resampling
function generateThumbnail($gd) {
$gd->setQuality(90);
return $gd->resizeByWidth(288);
}
...}
And in the template the real magic happens:
<div class="headerimg1" style="background:url(<% control grabHeaderImage(1) %>$URL<% end_control %>) top center no-repeat;"></div>
<div class="headerimg2" style="background:url(<% control grabHeaderImage(2) %>$URL<% end_control %>) top center no-repeat;"></div>
Note that if you don't need the parent->parent loop then calling the following from the template works with the new generateThumbail function:
$HeaderImage1.Thumbnail.URL
Inspired by: http://doc.silverstripe.com/doku.php?id=imageupload
Hope this helps somebody! Any comments/suggestions are welcome :-)