2
votes

Ok, so this has been driving me crazy for the past couple days...
I have a DataObject like so:

private static $db = array(
    // other properties
    'active' => 'Boolean',
    'sort' => 'Int' // ID of another DataObject of this type, after which it is to be displayed.
);
private static $has_one = array('Page' => 'CustomPage');

The CustomPage just extends Page and has a has_many relationship with this DataObject.
The pain now for me is to get the data in a way that they're correctly sorted.

EDIT: The sort value is actually the ID of the DataObject after which to sort this one.

For example given the following:

ID    sort
1      0
2      3
3      5
4      1
5      1

The result should be ordered like this:

ID
1
4
5
3
2

The sort can be duplicated, since I don't really want to bother with updating every item whenever I just add something in the middle.

2

2 Answers

2
votes

One way to set the sort order of a DataObject is to set the $default_sort variable:

class CustomDataObject extends DataObject {

    private static $db = array(
        'Active' => 'Boolean',
        'SortOrder' => 'Int'
    );

    private static $has_one = array(
        'Page' => 'CustomPage'
    );

    private static $default_sort = 'SortOrder ASC';
}

Make sure you call ?flush=all after doing this to clear the site cache.

Also, if the custom DataObject is being maintained through a GridField we can use module to control the sort order through drag and drop. Here is a StackOverflow answer detailing how to use one of these modules: Silverstripe DataObject - drag and drop ordering

0
votes

As 3dgoo stated $default_sortis your friend. When your column sort (or SortOrder) isn't unique you can always add another column to sort duplicates, so something like

private static $default_sort = 'sort, ID ASC';

should work in your case.