Reputation: 4424
Our Silverstripe project has the following two page types:
class MultiSectionPage extends Page {
private static $allowed_children = array(
'Section'
);
public function PageSections() {
$PageSections = Section::get()->filter(array('ParentID' => $this->ID));
return $PageSections;
}
}
class Section extends Page {
public static $allowed_children = array();
private static $show_in_sitetree = false;
}
In the Layout/MultiSectionPage.ss template the following code loops through each child Section as a dataobject:
<% loop $PageSections %>
<% include MultiSectionPage_Section %>
<% end_loop %>
I want to make sure that if anyone accidentally links to a Section it redirects to the parent MultiSectionPage.
class Section extends Page {
public function Link() {
return parent::Link() . '#section-' . $this->ID;
}
}
class Section_Controller extends Page_Controller {
public function init(){
parent::init();
if(!$this->getResponse()->isFinished() && $link = $this->Link()) {
$this->redirect($link, 301);
return;
}
}
}
However using this method triggers a redirect even when viewing the MultiSectionPage as the init must get called each time the Section DataObject is rendered.
How do I detect whether a Section Controller is being loaded as a standalone parent (redirect) or as child of a MultiSectionPage ?
Upvotes: 2
Views: 1334
Reputation: 15804
The Section_Controller
should not be getting called when viewing the MultiSectionPage
. Only the Section
object is loaded when looping through PageSections
. When retrieving a DataList
of DataObjects
only their class is loaded, not their controller.
Note the Section_Controller
should redirect to the parent page link, not the current page link. I would also recommend updating the Section
Link
function to return the parent link:
class Section extends Page {
private static $allowed_children = array();
private static $show_in_sitetree = false;
public function Link($action = null) {
return $this->Parent()->Link($action);
}
}
class Section_Controller extends Page_Controller {
public function init() {
parent::init();
return $this->redirect($this->Parent()->Link(), 301);
}
}
Upvotes: 3