6

I have a DataObject with a default sort:

class Author extends DataObject {
    private static $db = array('Name' => 'Varchar');
    private static $default_sort = 'Name ASC';
}

I want to Author::get() the data but with no sort.

so given...

Author::create(array('Name' => 'DEF'))->write();
Author::create(array('Name' => 'ABC'))->write();

This would output ABC then DEF using the sort, but if the sort was cleared I'd expect DEF then ABC.

I've tried Author::get()->sort('') and Author::get()->sort(null) but both return ABC then DEF again.

Note The reason I'm asking is that I have a complex query (using joins) where this is causing an issue and I'm getting an error with it if I try and set the sort too.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY "_SortColumn0" ASC' at line 1

So the solution, and what I'd like to know anyway, is how to clear the default sort for the specific Author::get() while keeping the existing default sort on the DataObject?

Barry
  • 3,303
  • 7
  • 23
  • 42
  • `private static $default_sort = 'Name DESC';` – Alive to die - Anant Aug 17 '16 at 10:12
  • Thank you @Anant but no, I want to keep the default sort for all other cases. – Barry Aug 17 '16 at 10:15
  • Have you tried `->sort(null)`? I haven't tested this. – 3dgoo Aug 17 '16 at 10:59
  • @3dgoo I had, sorry, didn't add that to the question the sort function just returns if you don't pass it something to sort with. – Barry Aug 17 '16 at 11:08
  • If you want the order the items have been created, why not sort by ID or Created ? – wmk Aug 18 '16 at 09:20
  • @wmk I state in the question that I'm after *no* sort being applied, it looks the same as "sort by XYZ" but it isn't it is *no sort* which is why I've accepted Dans answer as it removes the default sort – Barry Aug 18 '16 at 09:58
  • 1
    BTW, I agree that setting `->sort(null)` should really unset the sort - would you like to open an issue (or even PR) on GitHub for this? – Dan Hensby Aug 18 '16 at 10:47
  • @DanHensby done.. https://github.com/silverstripe/silverstripe-framework/issues/5897 – Barry Aug 18 '16 at 11:11

1 Answers1

5

I think the only way to unset the sort would be to manipulate the DataQuery that underpins the DataList which is returned when running Author::get().

$dq = Author::get()->dataQuery();
$dq->sort(null, null, true);
$authors = Author::get()->setDataQuery($dq);
Dan Hensby
  • 1,118
  • 6
  • 11