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

Page Controller - Query if page has a certain parent


Reply


3 Posts   1767 Views

Avatar
njprrogers

Community Member, 23 Posts

22 April 2011 at 4:02am

Hi,

I have my page_controller and I wish to find out whether the current page is in a particular section (similar to InSection in the templating layer!).

Can anyone advise how I would go about this?

Thanks!

Nick

Avatar
swaiba

Forum Moderator, 1799 Posts

22 April 2011 at 4:54am

Anything that you see in the template is really a function within the controller...

in this case the SiteTree controller so in any page you can type

if ($this->InSection('xyz')) {
//do stuff
}

Avatar
Ben_W

Community Member, 80 Posts

28 April 2011 at 12:21pm

I usually create one page type for each root level page, or key page, most of time place holder pages, and limit the occurrence of these page to one instance only by adding the following.

class ApplicationPageHolder extends Page {
...

//only allow one instance
   public function canCreate() {
      return !DataObject::get_one("SiteTree", "ClassName ='ApplicationPageHolder'");
   }
...

}

Example of site tree:

ApplicationPageHolder
- ApplicationPage
- ApplicationPage
- ApplicationPage
GalleryPageHolder
- ImageGalleryPage
- VideoGalleryPage

In the Page.php Controller, you may add these functions.

class Page_Controller extends ContentController {
...

/**
    * get root parent page
    */
   function FinalParent($page = null) {
      if(!$page){
         $page = $this;
      }
      if($page->ParentID > 0) {
         return $this->FinalParent($page->Parent());
      }
      else {
         return $page;
      }
   }

function FinalParentClassName(){
      //get root parent page id
      $parent_page = $this->FinalParent();
      $parent_page_class_name = $parent_page->ClassName;
      
      return $parent_page_class_name;
   }
...

}

Now in the ApplicationPage.ss you can do

<% if FinalParentClassName = ApplicationPageHolder%>
display something
<% end_if %>

You may also create your own function in Page_Controller to do some specific check you need, just use FinalParent() which always return the root level page. The advantage of doing this (creating individual page type for each root level page) is that URLSegment can be changed due to user update, whereas ClassName will always stay as it is.

Hope this helps.