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.

Data Model Questions

Accessing Parents Parent information


Reply

4 Posts   4675 Views

Avatar
obj63mc

6 January 2010 at 6:48am Community Member, 24 Posts

Hi All,

I am trying to access an objects parent parent. For example. I have a homepage that has a featured article. The article is in a structure of Category >> Sub Cat >> Article. So I can access the parent of the article to get the sub category - $FeaturedArticle.Parent.Link

When I try $FeaturedArticle.Parent.Parent.Link though this will then simply return an error stating the forTemplate method is not available for category to render. Because of this I added the forTemplate method but then nothing returns at all when I call it. No errors, nothing. My forTemplate function is below, any idea when I then call $FeaturedArticle.Parent.Parent nothing displays on my .ss template? Also does anyone know a better way to access this data from the $FeaturedArticle variable that I have.

function forTemplate() {
      $whereStatement = "CategoryPage_Live.ID = " . $this->ID; // Select the current category
$orderBy = null;
$limit = null;
$join = null;

//$whereStatement = "ParentID = ".$this->ParentID." AND ID <> ".$this->ID;
$cat = DataObject::get("CategoryPage", $whereStatement, $orderBy, $join, $limit);
      
      $string = '<a href="'.$cat->Link.'">'.$cat->Title.'</a>';
      return $string;
   }

Avatar
Willr

6 January 2010 at 9:21am Forum Moderator, 5511 Posts

Not sure the template parser supports that level of nested commands (Parent.Parent). You probably have to wrap it in a control

<% control FeaturedArticle %>
<% control Parent %>
$Parent.Link
<% end_control %>
<% end_control %>

Avatar
wee-man

8 January 2010 at 11:01am Community Member, 21 Posts

I think Willr is right.
But it makes the templates "ugly" ;)

If i have such a situation i use delegate-methods to avoid control..control..control blocks in the templates.
For example FeaturedArticle

function Category() {
return $this->Parent()->Parent();
}

Now the template looks like this

$Category.Link

Avatar
obj63mc

8 January 2010 at 11:19am Community Member, 24 Posts

Thanks all, these solutions work perfectly.