Remove DataObject default sort
Asked Answered
S

1

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?

Sycosis answered 17/8, 2016 at 10:10 Comment(8)
private static $default_sort = 'Name DESC';Autotransformer
Thank you @Anant but no, I want to keep the default sort for all other cases.Sycosis
Have you tried ->sort(null)? I haven't tested this.Alyose
@Alyose 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.Sycosis
If you want the order the items have been created, why not sort by ID or Created ?Cooke
@Cooke 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 sortSycosis
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?Twinscrew
@DanHensby done.. github.com/silverstripe/silverstripe-framework/issues/5897Sycosis
T
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);
Twinscrew answered 17/8, 2016 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.