How to sort in grails list? - sorting

I just started with grails and would like to sort a list by descending date. I tried this:
<g:sortableColumn property="eventStartDate" defaultOrder="asc" title="${message(code: 'event.eventStartDate.label', default: 'Event Start Date')}" />
However this does not sort the list. The controller looks like this:
def list = {
params.max = Math.min(params.max ? params.int('max') : 10, 100)
[eventInstanceList: Event.list(params), eventInstanceTotal: Event.count()]
}
How can I sort by descending eventStartDate?

The reason it might not have worked is:
Event.list(params) retrieves everything.
You are sorting it in ascending order (asc) but you said you want to sort it in descending order (desc).
Solution:
Change the second line of your controller action to:
[eventInstanceList: Event.list(order: "desc"), eventInstanceTotal: Event.count()]
More info:
http://grails.github.io/grails-doc/2.2.1/ref/Domain%20Classes/list.html
Event.list(params) returns every thing in the domain object. It doesn't do any filtering. Use findAllBy* or findBy* or createCriteria instead.
Example:
Event.findAllByNameAndDate(params.get("name"), params.get("date"), [max: 10, order: "desc"])
More info:
grails domain class .list() method with params

Related

Incorrect sort of DB query results in micronaut project

I am passing this to the repository function:
Pageable.from(offset, limit).order(Sort.Order(orderBy, direction, true))
It works just fine if orderBy is the name of a String property. If I try to sort by a number property it will return the results ordered as:
1,
11,
12,
...
19,
2,
20,
21
Any suggestions on how to fix for the number ordering?
Doing the sort on the method name (such as findAllOrderByNameAsc) is not an option because this is a parameter that comes from the API. We need to support ordering by any property.
remove the ignoreCase=true parameter or pass it as false
Sort.Order(orderBy, direction, true)
you should use ignoreCase only on String fields

Sort Collection By id set

I have an array of ids that i want to sort a given column by them in the collection.
For example,
$suppliersOrder = [8,7,5,1,3,4];
$items = Items::get()->sortBy(function($model) use ($suppliersOrder) {
return array_search($model->supplier_id, $suppliersOrder);
})->values();
This acts like ordering items as [1,3,4,5,7,8] instead of the given order. And if I try sortByDesc, likewise [8,7,5,4,3,1] but I couldn't figure out the way to actually sort them as my given array's order.
My ultimate goal is then running $items->groupBy('supplier.name') so I can have my desired order.
What Alexander Villalobos suggested in the comments, I changed my code like this:
$items = Items::get()->sortBy(function($model) use ($suppliersOrder) {
return rsort($model->supplier_id, $suppliersOrder);
});
Indirect modification of overloaded property App\Item::$supplier_id has no effect
$suppliersOrder = [8,7,5,1,3,4];
$items = Items::get()->sortBy(function($row,$key) use ($suppliersOrder) {
return array_search($row->supplier_id, $suppliersOrder);
});
This should give you sorted collection of items by the order you described in $suppliersOrder. As per Laravel docs, the parameters to the callback function include one being the row for the collection and another being the key of that row in the collection.

Realm React native sorted order

Basically I have a MessageSchema with a date property, on my app I need to query all the messages stored on the database and be able to sort them by their date to display them on a ListView, I do the query as follows:
return realm.objects("Message").sorted('date');
This works, but only one way, the messages are sorted on ascending order only, I haven't found a way to do it on descending order and the docs of the react native only show one example:
let hondas = realm.objects('Car').filtered('make = "Honda"');
// Sort Hondas by mileage
let sortedHondas = hondas.sorted('miles');
Any advice is welcome.
Versions:
react-native: "0.40.0"
realm js: "1.0.2"
return realm.objects("Message").sorted('date', true);
Looking at the source code you can see that the sorted method expects
a descriptor and a Boolean named reverse, that it is set as false unless
you change it, so the code above just reverses the order.

Sorting a NotesDocumentCollection based on a date field in SSJS

Using Server side javascript, I need to sort a NotesDcumentCollection based on a field in the collection containing a date when the documents was created or any built in field when the documents was created.
It would be nice if the function could take a sort option parameter so I could put in if I want the result back in ascending or descending order.
the reason I need this is because I use database.getModifiedDocuments() which returns an unsorted notesdocumentcollection. I need to return the documents in descending order.
The following code is a modified snippet from openNTF which returns the collection in ascending order.
function sortColByDateItem(dc:NotesDocumentCollection, iName:String) {
try{
var rl:java.util.Vector = new java.util.Vector();
var tm:java.util.TreeMap = new java.util.TreeMap();
var doc:NotesNotesDocument = dc.getFirstDocument();
while (doc != null) {
tm.put(doc.getItemValueDateTimeArray(iName)[0].toJavaDate(), doc);
doc = dc.getNextDocument(doc);
}
var tCol:java.util.Collection = tm.values();
var tIt:java.util.Iterator = tCol.iterator();
while (tIt.hasNext()) {
rl.add(tIt.next());
}
return rl;
}catch(e){
}
}
When you construct the TreeMap, pass a Comparator to the constructor. This allows you to define custom sorting instead of "natural" sorting, which by default sorts ascending. Alternatively, you can call descendingMap against the TreeMap to return a clone in reverse order.
This is a very expensive methodology if you are dealing with large number of documents. I mostly use NotesViewEntrycollection (always sorted according to the source view) or view navigator.
For large databases, you may use a view, sorted according to the modified date and navigate through entries of that view until the most recent date your code has been executed (which you have to save it somewhere).
For smaller operations, Tim's method is great!

Rearranging active record elements in Yii

I am using a CDbCriteria with its own conditions, with & order clauses. However, the order i want to give to the elements in the array is way too complex to specify in the order clause.
The solution i have in mind consists of obtaining the active records with the defined criteria like this
$theModelsINeed = MyModel::model()->findAll($criteria);
and then rearrange the order from my php code. How can i do this? I mean, i know how to iterate through its elements, but i donĀ“t know if it is possible to actually change them.
I have been looking into this link about populating active records, but it seems quite complicated and maybe someone could have some better advice.
Thanks
There is nothing special about Yii's active records. The find family of methods will return an array of objects, and you can sort this array like any other array in PHP.
If you have complex sort criteria, this means that probably the best tool for this is usort. Since you will be dealing with objects, your user-defined comparison functions will look something like this:
function compare($x, $y)
{
// First sort criterion: $obj->Name
if ($x->Name != $y->Name) {
return $x->Name < $y->Name ? -1 : 1; // this is an ascending sort
}
// Second sort criterion: $obj->Age
if ($x->Age != $y->Age) {
return $x->Age < $y->Age ? 1 : -1; // this is a descending sort
}
// Add more criteria here
return 0; // if we get this far, the items are equal
}
If you do want to get an array as a result, you can use this method for fetching data that supports dbCriteria:
$model = MyModel::model()->myScope();
$model->dbCriteria->condition .= " AND date BETWEEN :d1 AND :d2";
$model->dbCriteria->order = 'field1 ASC, field2 DESC';
$model->dbCriteria->params = array(':d1'=>$d1, ':d2'=>$d2);
$theModelsINeed = $model->getCommandBuilder()
->createFindCommand($model->tableSchema, $model->dbCriteria)
->queryAll();
The above example shows using a defined scope and modifying the condition with named parameters.
If you don't need Active Record, you could also look into Query Builder, but the above method has worked pretty well for me when I want to use AR but need an array for my result.

Resources