Jump to:

3450 Posts in 1063 Topics by 738 members

Data Model Questions

SilverStripe Forums » Data Model Questions » Sorting Children

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

Page: 1
Go to End
Author Topic: 1026 Views
  • SeanBoy
    Avatar
    Community Member
    8 Posts

    Sorting Children Link to this post

    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.

  • Willr
    Avatar
    Forum Moderator
    5497 Posts

    Re: Sorting Children Link to this post

    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.

  • SeanBoy
    Avatar
    Community Member
    8 Posts

    Re: Sorting Children Link to this post

    Thanks Willr. Much appreciated.

    1026 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.