PDA

View Full Version : How to remotely sort an Ext grid column that renders a nested model?



James Quall
9 Feb 2013, 6:18 AM
I asked this question on StackOverflow, but thought it might be better to try here.

I have two models, Product and Manufacturer:



Ext.define('Manufacturer', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'},
],
});

Ext.define('Product', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'},
{name: 'manufacturer', type: 'Manufacturer'}, // i.e. nested object
],
});

I display Products in an Ext.grid.Panel, like so:


Ext.create('Ext.grid.Panel', {
title: 'Products',
...
remoteSort: true,
columns: [
{text: 'Id', dataIndex: 'id', sortable: true},
{text: 'Name', dataIndex: 'name', sortable: true},
{text: 'Manufacturer', dataIndex: 'manufacturer', sortable: true, renderer: function(manufacturer) {
return manufacturer.name; // render manufacturer name
}
},
],
});

As you can see, all three columns are configured to be sortable, and I am using remote sorting. This works for the first two columns, but the third column (manufacturer) is giving me trouble.

For instance, when a user sorts the Product grid by name, Ext sends the following JSON to the server:


{ sort: [{property: 'name', direction: 'ASC'}] }

This is fine, because the server knows to simply sort by each Product's name property.

But when a user sorts the Product grid by manufacturer, the JSON sent is:


{ sort: [{property: 'manufacturer', direction: 'ASC'}] }

Obviously, this does not give the server any idea which property of the manufacturer's it should sort by! Is it the manufacturer's id? Or is it it's name? Or something else?

For my grid, since I render the manufacturer's name, I'd like to sort it by name. But I see no way to tell the server this. And I certainly don't want to make my server just sort by the manufacturer's name all the time.

If the JSON was sent like this it would be ideal:


{ sort: {[property: 'manufacturer.name', direction: 'ASC'}] }

Sadly, Ext does not seem to do that (?). So, what's the solution?

existdissolve
10 Feb 2013, 9:24 PM
I have a grid where I use a fake dataIndex to render the grid column in a user friendly way. As you've found out, by default, the grid will sort by the dataIndex which, in cases like yours and mine, are not ideal...in my case, the grid would send through a sort parameter for a column that, server side, does not actually exist.

So what I do is simply override getSortParam() (http://docs.sencha.com/ext-js/4-1/source/Column3.html#Ext-grid-column-Column-method-getSortParam) on the column. This allows me to specify the property by which I'd like to remotely sort the grid...in my case, I use colons (e.g., Manufacturer:Name), but the concept is the same.

James Quall
10 Feb 2013, 10:11 PM
Thanks, that's exactly what I was looking for.