Jump to:

3373 Posts in 999 Topics by 712 members

Data Model Questions

SilverStripe Forums » Data Model Questions » SOLVED: Return data set grouped by month

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

Page: 1
Go to End
Author Topic: 1535 Views
  • LesC
    Avatar
    Community Member
    70 Posts

    SOLVED: Return data set grouped by month Link to this post

    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

  • banal
    Avatar
    Community Member
    901 Posts

    Re: SOLVED: Return data set grouped by month Link to this post

    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.

  • LesC
    Avatar
    Community Member
    70 Posts

    Re: SOLVED: Return data set grouped by month Link to this post

    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!

  • bobdylansbeard
    Avatar
    Community Member
    4 Posts

    Re: SOLVED: Return data set grouped by month Link to this post

    Great solution. Thanks.

    1535 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.