When we have 50,000 records in grid or just going to have but do not really have (as we work with Smart Rendering, with Dynamic Loading) client side sorting will not help a lot. Our grid just doesn't know all the values yet. So we need to move sorting to server side. How? Just relax. It is really simple.
There will be 3 stages of the plan:
To cancel client side sorting we need to enable sorting for the columns first. Like it was described in the previous tutorial, you can do this with setColSorting method, but the sorting type for all three columns will be “server”:
mygrid.setColSorting("server,server,server");
The “server” sorting type means nothing for sorting routine of the grid, so it'll just ignore it. This information is mostly for myself as column sorting was moved to server side. Put this command somewhere before mygrid.init() . Now we are ready to execute stages 1 and 2 of the plan. We'll do this with onBeforeSorting event handler. First let's define the handler function. According to events documentation it gets 3 incoming arguments:
And this function will work IN PROFESSIONAL EDITION of the grid. Only. Sorry, from now on only those who “got the tickets” go further… OK, if you are still reading, here is the complete code for the event handler function. Put it into the script block we've left for functions (or in any other one):
function sortGridOnServer(ind,gridObj,direct){ mygrid.clearAll(); mygrid.loadXML(gridQString+(gridQString.indexOf("?")>=0?"&":"?")+"orderby="+ind+"&direct="+direct); mygrid.setSortImgState(true,ind,direct); return false; }
The above mentioned code does the following:
Now when we have sortGridOnServer function, we can add the following command to set the event handler to grid initialization script:
mygrid.attachEvent("onBeforeSorting",sortGridOnServer);
Server side changes are simple, as we just add Order by statement for the field in table that corresponds to a column in grid, and set the direction: ASC if asc, DESC if des. Here is a code sample for PHP:
//order by $columns = array("nm","code","num_val"); if(isset($_GET["orderby"])){ if($_GET["direct"]=='des') $direct = "DESC"; else $direct = "ASC"; $sql.=" Order by ".$columns[$_GET["orderby"]]." ".$direct; }