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

SOLVED: Return data set grouped by month


Reply

4 Posts   1672 Views

Avatar
LesC

18 November 2009 at 12:47am (Last edited: 18 November 2009 4:07am), Community Member, 70 Posts

I'm trying to get a page to display items grouped by their date field, so that I get something like:

JANUARY 2010
Item title
Item title

MARCH 2010
Item title

APRIL 2010
Item title
Item title

Where do I start with this? I can work out how to return stuff grouped on a category relationship, or by first letter, but how do you handle date ranges?

Cheers

L

Avatar
banal

18 November 2009 at 1:37am Community Member, 901 Posts

Hi

Here's how I solved this in a project of mine.
On the DataObject, add the following code:

private static $currMon;

public function CurrentMonth(){
   $month = strftime('%B %Y', strtotime($this->Date));
   if($month == self::$currMon){
      return false;
   } else {
      self::$currMon = $month;
      return utf8_encode($month);
   }
}

This will return the current month (incl. year) as string whenever the date changes. Otherwise false will be returned.
Now all that's left to do is to get a list of DataObjects sorted by Date (in the following example accessed via Dates, and iterate over it with the following template code:

<% control Dates %>
<% if CurrentMonth %>
<h2>$CurrentMonth</h2>
<% end_if %>
... your markup for each item ...
<% end_control %>

For completeness sake here's how the "Dates" method could look like:

public function Dates($limit = 100){
   return DataObject::get(
      'DataObjectClassName',
      $this->ClassName . 'ID = '. $this->ID,
      'Date ASC', '', $limit
   );
}

Make sure the items in red match your Item class and date field.

Avatar
LesC

18 November 2009 at 4:07am Community Member, 70 Posts

Thanks Banal,

I think I was over thinking things again - there's no need to actually group them, rather just show the title when needed? Genius!

Avatar
bobdylansbeard

1 October 2012 at 8:06pm Community Member, 4 Posts

Great solution. Thanks.