Sunday 28 April 2013

Custom Logic in Field Sorting for ListGrid in SmartClient

Sometime data in the ListGrid needs to be sorted on a particular condition or criteria rather then traditional sorted OR you get data is a form where it would not be possible for the ListGrid to sort it on its own. For this purpose, ListGrid provides a 'sortNormalizer' function which can be implemented at grid level or at field level for data sorting. Have a look at the following example :


<pre  style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-s003mlEAhvwIvXAlnBoXoBbBtuXAejNQN6vWliFgZ05CghIJkoK74Z2EkX0AaOMHLIANtFZ1rDCSZS4dcOwgvPu9zsTEl_0cUVC4O3EWLwYPKK_ttSiH7fVdWEztHK7rSlPKKZLfjE8Z/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> isc.ListGrid.create({ 
   ID: "countryList", 
   data: countryData, 
   fields:[ 
     {name:"countryCode", title:"Flag", width:50}, 
     {name:"countryName", title:"Country"}, 
     {name:"independence", title:"Nationhood", type:"date"}, 
     {name:"area", title:"Area (km&amp;sup2;)", type:"float", formatCellValue:"isc.Format.toUSString(value)"}, 
     {name:"gdp_percap", title:"GDP (per capita)", align:"right", 
       formatCellValue: function (value, record) { 
         var gdpPerCapita = Math.round(record.gdp*1000000000/record.population); 
         return isc.Format.toUSDollarString(gdpPerCapita); 
       }, 
       sortNormalizer: function (record) { 
         return record.gdp/record.population; 
       } 
     } 
   ], 
 }) 
</code></pre>

In the above example, notice how the sort normalizer function is used to sort values calculating ratio of a two of the fields of the record row.  Also notice that the value returned by the normalizer function is used for sorting is numeric which can easily by used for sorting. This concept can be used for sorting by any custom criteria or condition. Though it is not necessary to return a numeric value
, it is a safe bet.
Another important things about normalizer function is that it also accepts a context parameter. The full signature of the sortNormalizer function is

 ListGridField.sortNormalizer() (recordObject, fieldName, context)

where context can be any variable which needs to be passed to the function. One of the scenario in which it can be used is when the custom sorting has to be done on the result of a text search , where the text searched is passed on to the function in the context variable.