Reputation: 27
I have set a field called Colour in Page.php and for any child I would like to grab the parent colour or loop through till it finds a parent that does have the colour field set.
I have a function below which seems to work in 2.4 but I cannot get to work in SS3 which I call inside a loop in templates as $Inherited(Colour).
Your help is appreciated
public function Inherited($objName) {
$page = $this->owner->Data();
do {
if ($obj = $page->obj($objName)) {
if ($obj instanceof ComponentSet) {
if ($obj->Count()) {
return $obj;
}
} elseif ($obj instanceof DataObject) {
if ($obj->exists()) {
return $obj;
}
} elseif ($obj->exists()) {
return $obj;
}
}
} while ($page->ParentID != 0 && $page = $page->Parent());
}
Upvotes: 1
Views: 1881
Reputation: 1665
Assuming your Colour field is a database field and not a relationship to another data object, add the following method to your Page
class.
public function getColour() { // Try returning banners for this page $colour = $this->getField('Colour'); if ( $colour ) { return $colour; } // No colour for this page? Loop through the parents. $parent = $this->Parent(); if ( $parent->ID ) { return $parent->getColour(); } // Still need a fallback position (handled by template) return null; }
If colour is a related data object you could do much the same thing but use the getComponent
or getComponents
method in place of getField
in the code above. This should work on both Silverstripe version 2.4.x and 3.0.x.
This kind of operation, although useful, should probably be done sparingly or be heavily cached as it's recursive could conceivably happen on the majority of page loads, and change very infrequently.
Upvotes: 1
Reputation: 6094
i suppose you've had this function defined inside some DataObjectDecorator, as you're using $this->owner
to refer to the current page.
there is no more DataObjectDecorator in SilverStripe 3 (see http://www.robertclarkson.net/2012/06/dataextension-class-replacing-dataobjectdecorator-silverstripe-3-0/) so there are two possible solutions:
a) replace DataObjectDecorator by DataExtension
b) simply move the Inherited
function to your Page class, and replace $this->owner
by $this
Upvotes: 1