GSP tag g:sortableColumn is used for sorting list in Grails. A list by default shows all the rows stored in database. A user can sort the list ascending/descending order by clicking on that column header.
But the same thing do not works for a customized search result (Criteria Search). For example a search result fetch 6 of 10 rows from database. If you display the result by tag, clicking on the column header for sorting will display all the 10 sorted rows in place of 6. This is happened because search parameters are missing in result page. Lets see the example below: Suppose we have a Book Class, Saerch Cmd and a criteria search for this class
class Book {
Integer id
String name
Date entryDate
}
class BookController{
def search() {
def searchCmd = new BookSearchCmd()
return [searchCmd: searchCmd]
}
def result() {
def cmd = new BookSearchCmd()
bindData cmd: params
def crit = Book.createCriteria()
bookList = crit.list(params) {
if (cmd[id]) le(‘id’, cmd[id])
}
}
class BookSearchCmd{
Integer id
String name
Date entryDate
}
Now if the id parameter is 6 and there is 10 id 1..10 it will display 6 rows but when you try to sort the result using <g:sortableColumn> in result.gsp page it will display all 10 result as there is no params in the result page. In the code crit.list(params) works when it gets search paramter, otherwise it execute default list() method.
A easy way out of the problem is saving searchCmd in the session and re-use for sorting the customized search result while the request comes from result page (params.search indicates request from search page). Some minor modification of the above code can do it as following code:
class BookController{
def search() {
session.removeAttribute(“searchCmd”)
def searchCmd = new BookSearchCmd()
return [searchCmd: searchCmd]
}
def result() {
def searchCmd = session.getAttribute(“searchCmd”)
if (params.search || searchCmd==null) {
searchCmd = new BookSearchCmd()
bindData searchCmd: params
session.setAttribute(“searchCmd”, searchCmd)
}
def crit = Book.createCriteria()
bookList = crit.list(params) {
if (searchCmd[id]) le(‘id’, searchCmd[id])
}
}
By: Md. Shahjalal
23.783622
90.393635