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

Link that displays entries with a specific category


Reply

2 Posts   672 Views

Avatar
VictorH

4 May 2011 at 7:04am Community Member, 29 Posts

I have a dropdown navigation on my website header that displays categories for a news section. Similar to this.

News
- Category One
- Category Two
- Category Three

I want it so that when a user clicks on any of the category links it displays a page with all the news articles for that specific category.

Below is the code for what I have now.

NewsHolder.php

<?php

class NewsHolder extends Page {
   static $icon = 'themes/kc/images/treeicons/news';
   
   static $default_child = 'NewsPage';
   
   static $allowed_children = array('NewsPage');
}

class NewsHolder_Controller extends Page_Controller {
}

?>

NewsPage.php

<?php

class NewsPage extends Page {
   static $icon = 'themes/kc/images/treeicons/news';
   
   static $db = array(
      'Date' => 'Date',
      'Author' => 'Text'
   );
   
   static $many_many = array(
      'NewsCategories' => 'NewsCategory'
   );
   
   function getCMSFields() {
      $fields = parent::getCMSFields();
      
      $fields->addFieldToTab('Root.Content.Main', $dateField = new DateField('Date', 'Article Date (for example: 20/12/2011)'), 'Content');
         $dateField->setConfig('showcalendar', true);
         $dateField->setConfig('dateformat','dd/MM/YYYY');
      $fields->addFieldToTab('Root.Content.Main', new TextField('Author','Author Name'), 'Content');
      
      $categories = new ManyManyDataObjectManager(
         $this,
         'NewsCategories',
         'NewsCategory',
         array(
            'Name' => 'Name'
         ),
         'getCMSFields_forPopup'
      );
      
      $fields->addFieldToTab('Root.Content.Categories', $categories);
      
      return $fields;
   }
}

class NewsPage_Controller extends Page_Controller {}

?>

NewsCategory.php

<?php

class NewsCategory extends DataObject {
   static $db = array(
      'Name' => 'Text'
   );
   
   static $belongs_many = array(
      'NewsPage' => 'NewsPage'
   );
   
   function getCMSFields_forPopup() {
      $fields = new FieldSet();
   
      $fields->push (new TextField('Name'));
   
      return $fields;
   }
}

?>

Navigation.ss

...
<h2>Categories</h2>
<ul>
   <% control NewsCategories %>
      <li>$Name</li>
   <% end_control %>
</ul>
...

I've included this function in Page.php

function NewsCategories() {
      return DataObject::get('NewsCategory');
   }

Avatar
VictorH

10 May 2011 at 7:45am Community Member, 29 Posts

Any help would be appreciated.

Thanks.