Reputation: 1977
Sort of new to grails! I am currently working on grails 2.3.11
and I can't see why the following code is not working as intended!
def listCommodity() {
List<Commodity> commodities;
if (params.searchBox) {
commodities = Commodity.list().findAll {
it.name.toLowerCase().contains("${params.searchBox.toLowerCase()}") ||
it.type.name.toLowerCase().contains("${params.searchBox.toLowerCase()}") ||
(it.type.parent ? it.type.parent.name.toLowerCase().contains("${params.searchBox.toLowerCase()}") : false)
}
} else {
commodities = Commodity.list()
}
commodities?.sort { one, two ->
if ("decs" == params?.order) {
return two.name <=> one.name
} else {
return one.name <=> two.name
}
}
def max = Math.min((params.max ?: 10) as Long, 100)
def offset = Math.min((params.offset ?: 0) as Long, commodities.size() - 1)
if (!commodities) {
flash.message = "No Items found Here!"
return [commodities: [], commoditiesCount: 0]
} else {
return [commodities: commodities[offset..Math.min(offset + max, commodities.size() - 1)], commoditiesCount: commodities.size(), searchBoxText: params.searchBox ?: '']
}
}
view:
....
<tr>
<g:sortableColumn params="${[searchBox:searchBoxText]}" property="name" title="${message(code: 'commodity.commodity.name.label', default: 'Name')}" />
</tr>
....
<% println commodities //here it prints the items in ascending %>
<g:each in="${commodities}" status="i" var="com">
<tr class="${(i % 2) == 0 ? 'even' : 'odd'}">
<td>
${com?.getName(lang)}
</td>
</tr>
</g:each>
....
this test passes:
given:
mockDomain(CommodityType,[[name: "Cereals"],[name: "Group", parent: new CommodityType(name: 'Corea')]])
mockDomain(Commodity,
[[name:"Kea", type:CommodityType.findByName("Cereals")],
[name:"Shiro", type:CommodityType.findByName("Cereals")],
[name:"Other with ea", type:new CommodityType(name: "Grass")],
[name:"Barely", type:CommodityType.findByName("Group")],
[name:"Teff",type:CommodityType.findByName("Cereals")]])
when:
params.order = "decs"
params.searchBox = "ea"
def models = controller.listCommodity()
then:
5 == models.commodities.size()
"Barely" == models.commodities[-1].name
"Teff" == models.commodities[0].name
"ea" == models.searchBoxText
when:
params.order = "asc"
params.searchBox = "ea"
def models2 = controller.listCommodity()
then:
5 == models2.commodities.size()
"Barely" == models2.commodities[0].name
"Teff" == models2.commodities[-1].name
"ea" == models2.searchBoxText
but when i test it on the browser! The sorting doesn't do anything! The i did a println on the view and the list is never sorted! What am i doing wrong?
Upvotes: 0
Views: 63
Reputation: 320
Two things to check :
sort(boolean, closure)
with true in the 1st argument to sort the list itself, otherwise a copy is createdGood luck!
Upvotes: 2