user2219915 user2219915 - 1 month ago 12
Javascript Question

Dojo datagrid: sort by first value in cell layout

I have used a formatter to add some html (a link, a break and a span) on or around different values. The issue now is that the column does not sort. I think it is because every cell in the column starts with the same value (a link with the same url. Eventually the urls will be different).

Here is the data:

{id: 1, 'main': 'puma', 'description': 'A puma is a cat', 'url': 'http://www.google.com', 'filesize': '12.34', date: '2010-01-01'},
{id: 2, 'main': 'tiger', 'description': 'Tiger, another cat', 'url': 'http://www.google.com', 'filesize': '43.27', date: '2013-03-04'},
{id: 3, 'main': 'Wombat', 'description': 'wombat, not a cat', 'url': 'http://www.google.com', 'filesize': '59.01', date: '2011-03-08'}


This is for the layout (left out the other columns from this sample):

{name: 'Title', fields: ['main','description','url','filesize'], 'width': '200px',formatter: formatLink}


And this is the formatter:

function formatLink(value){
return '<a href="'+ value[2] +'">'+value[0]+'</a><br />'+value[1]+'<span class="smalltxt">&nbsp;File Size:&nbsp;' + value[3] + 'MB</span>';
}


For clarity, to see it all in action: http://jsfiddle.net/QXYDK/6/

Ideally I would not have all this stuff in the same cell, but it required for this project.

The center column does not sort at all at the moment. Is there a way I can choose to sort by value[0] (the first field, 'main')?

Answer

I don't know if it's a bug in Dojo or not, but Dojo only defines sorting on the field attribute. But because you're using a custom field with a formatter, you only use fields and not field.

The solution is to define the field you want to sort on (in this case "main").

The code for your layout would become:

var layout = [
    {name: 'Index', field: 'id'},
    {name: 'Title', fields: ['main','description','url','filesize'],field: 'main', 'width': '200px',formatter: formatLink},
    {name: 'Date', field: 'date', width: 10, formatter: formatDate}
];

By default, Dojo sorts your data case sensitive, which means that Wombat (which starts with a capital) will be sorted differently than puma and tiger (which start with a lower case letter). To enable case insensitive sorting, you need to define a comparatorMap on your store, for example:

store.comparatorMap = new Object();
store.comparatorMap["main"] = function(a, b) {
    if (a.toLowerCase() < b.toLowerCase()) {
         return -1;   
    } else if (a.toLowerCase() == b.toLowerCase()) {
        return 0;
    } else {
        return 1;
    }
};

I also updated your JSFiddle with this new information. The result can be found here.

Comments