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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

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

Sorting Children


Go to End


3 Posts   1736 Views

Avatar
SeanBoy

Community Member, 8 Posts

22 January 2011 at 10:39am

Edited: 22/01/2011 11:06am

I am trying to sort a sub list of records which are children of a many relationship. I am really struggling with this, having tried quite a few suggestions in the forums but to no avail. Could anyone help me with this please?

I have a very simple example below to explain my issue. Apologies for no indentation, I cant figure out how to do that. Any clues?

An author has many books. Both data objects are seen below:

class Author extends DataObject {

  static $db = array(
      'Name' => 'VARCHAR(50)',);

  static $has_many = array('Books' => 'Book');
}

class Book extends DataObject {

  static $db = array(
      'Name' => 'VARCHAR(50)',);

  static $has_one = array(
      'Author' => 'Author');
}

To output, I have the following in my template:

<% control Author %>
    <b>Name: $Name</b><br/>
      <% control Books %>$Name<br/>
  <% end_control %>

And within my controller class I have the following:

public function getAuthor() {
    $authorObjects = DataObject::get("author");
    return $authorObjects;
  }

What I get back when I browse the page is:

Name: Stephen King
The Stand
Insomnia
Bag of Bones
Name: Gerald Seymour
Home Run

The books are not sorted and I just cant figure out what to do. Sorting Authors is not an issue.

Thanks in advance.

Avatar
Willr

Forum Moderator, 5523 Posts

22 January 2011 at 12:42pm

You can specifiy a $default_sort on any dataobject which all DataObject::get() calls should use.

class Book extends DataObject {

static $default_sort = "Name ASC";

...
}

You may need to ?flush=1 after changing that for the template to update.

Avatar
SeanBoy

Community Member, 8 Posts

22 January 2011 at 9:27pm

Thanks Willr. Much appreciated.