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 /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

SOLVED: Return data set grouped by month

Go to End

6 Posts   3287 Views


Community Member, 70 Posts

18 November 2009 at 12:47am

Edited: 18/11/2009 4:07am

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

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?




Community Member, 904 Posts

18 November 2009 at 1:37am


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 %>
<% 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(
		$this->ClassName . 'ID = '. $this->ID, 
		'Date ASC', '', $limit

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


Community Member, 70 Posts

18 November 2009 at 4:07am

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!


Community Member, 5 Posts

1 October 2012 at 8:06pm

Great solution. Thanks.


Community Member, 1 Post

20 November 2014 at 5:09am

Edited: 20/11/2014 5:29am

Inside loop function's not working in SS3 or I'm not read something:

For me this is working:

private static $currMon = 'NILL';
public function CurrentMonth($last,$ide){
if($last == self::$currMon){
	 return 0;
} else {
	 self::$currMon = $last;
	 return 1;


<% loop Dates %>
<% if $Top.CurrentMonth($Dat.month,$ID) %>
<div class="col-xs-12">$Dat.month</div>
<% end_if %>

<% end_loop %>

Without passing $ID variable function will be cached by template engine

ps. this forum is Overly Attached with this crapy captcha


Community Member, 2 Posts

4 June 2015 at 12:53am

Sorry for digging this out, I stumbled over it while searching. Just for Info, I think a GroupedList fits perfectly in this case ->