How to remotely sort an Ext grid column that renders a nested object? - javascript

Simple question here, and I'm really surprised I cannot find an answer to it anywhere.
I have the following product model:
Ext.define('Product', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'},
{name: 'manufacturer', type: 'auto'}, // i.e. nested object literal
],
});
As can be seen, a product has a nested object inside it that contains details about a manufacturer (id, name, description, etc.).
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 grid by product 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 grid by manufacturer, the JSON sent is:
{ sort: [{ property: 'manufacturer', direction: 'ASC' }] }
Since the manufacturer is an object, this does not give the server any idea which property of the manufacturer it should sort by! Is it the manufacturer's id? Or is it the manufacturer'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?

Okay, I asked on the Sencha Forums and got a response. It appears you can override getSortParam() in the column config. Example:
columns: [
...
{
header: 'Manufacturer',
dataIndex: 'manufacturer',
sortable: true,
renderer: function(manufacturer) {
return manufacturer.name; // render manufacturer name
},
getSortParam: function() {
return 'manufacturer.name';
},
}
...
]
This will send the ideal JSON I described in my OP. Now I just need to make my server parse this properly! :)

Related

Sencha: How to use data from one file to another

Im new at this sencha thingy and im trying to experiment a bit with it. I've been making some very simple tests and now i've reached the point where i want to pass the data from one file to another. To make it easier to understand im trying to get the data from the following text box to make a simple filter tool.
the textfield has been created in the following piece of code in the file Filters.js
Ext.define('Prj01Filtro.view.main.Filters', {
extend:'Ext.form.Panel',
xtype: 'Filters',
alias: 'form.formFilter',
requires: [
'Prj01Filtros.view.main.FilterController'
],
controller: 'controllerFilter',
items:[
{
margin: '0 0 10 0',
buttons: [
{
xtype: 'textfield',
fieldLabel: 'Filter',
name: 'textFieldSearch'
}, {
name: 'buttonSearch',
text: 'Buscar',
listeners: {
click: 'onClickFilter'
}
}, {
name: 'buttonRemoveFilter',
text: 'X',
listeners: {
click: 'onClickRemove'
}
}
]
}
]
The code of the buttons have been located in a file named FilterController.js
Ext.define('Prj01Filtros.view.main.FilterController',{
extend: 'Ext.app.ViewController',
alias: 'controller.controllerFilter',
onClickFilter: function() {
//Code to apply the filter
},
onClickRemove: function() {
//code to remove the filter
}
})
Finally the code of the table is located in a file named List.js
Ext.define('Prj01Filtros.view.main.List', {
extend: 'Ext.grid.Panel',
xtype: 'mainlist',
plugins: 'gridfilters',
requires: [
'Prj01Filtros.store.Personnel'
],
title: 'Personnel',
store: {
type: 'personnel'
},
columns: [
{ text: 'Name', dataIndex: 'name', align: 'left', filter: {
type: 'string'
}},
{ text: 'Email', dataIndex: 'email', flex: 1, align: 'left', filter: {
type: 'string'
}},
{ text: 'Phone', dataIndex: 'phone', flex: 1, align: 'left', filter: {
type: 'string'
}},
],
listeners: {
select: 'onItemSelected'
},
});
So my goal is to make a function in FilterController.js that can be called from Filters.js which sets the value for the filters applied in the columns of List.js but im kind of stuck on how to set the value property for the filter from the function that i have created. If someone knows how to do it i would appreciate the help. Thanks!
I've tried many things but since im new to sencha im pretty much sure that they were incorrect anyways.
I suggest to study View Models & Data Binding and ViewModel Internals sections of Ext JS documentation. These are among the most powerful features of Ext JS so it good to develop a deep understanding.
For you current question, you need to access the store behind your List view to manage the filters, not the list itself. Once you get the store, you can set / clear the filters with setFilters and clearFilter methods on the store:
store.setFilter([{
property: 'email',
value: '<search term here>',
operator: 'like'
}]);
store.clearFilter();
To easily access the store, define the store in the view model of a view that is above both List and Filters view. This is the important part because this way you can take advantage of inheriting the view model from the container parent. Let's say you have a panel which contains both List and Filters. Define the store in the view model:
stores: {
personnel: {
type: 'personnel'
}
}
Use bind config when assigning the store in your List:
Ext.define('Prj01Filtros.view.main.List', {
...
bind: {
store: '{personnel}'
}
...
});
After all this, you can access the store from the Filters view controller's methods:
onClickFilter: function() {
this.getViewModel().getStore('personnel').setFilters(...);
}
You need the get the value the user entered into the field. You can access it from the controller with querying the textfield component, but you can also do it with the view model.

How to create a dynamic (on the fly) form in Sencha Touch

I am working in a sencha touch ap and I need to generate views with dynamic forms.
Configuration comes from the backend (JSON) and depending of this I paint a component or other.. for example:
"auxiliaryGroups": [
{
"id": "1000",
"name": "Basic Data",
"fields": [
{
"id": "1001",
"name": "Company name",
"editable": true,
"mandatory": true,
"calculation": true,
"internalType": "T",
"type": "textfield",
"options": []
}
]
}
],
Where type is related xtype in Sencha.
In the view I am creating all options of fields:
{
xtype : 'fieldset',
itemId: 'auxiliaryFieldsGroup3',
title: 'Requirements',
//cls : 'headerField',
items:[
{
xtype: 'togglefield',
name: 'f6',
label: 'Auxiliary field R1'
},
{
xtype: 'selectfield',
name: 'f10',
label: 'Auxiliary field R5',
placeHolder: 'Select one..',
options: [
{text: 'First Option', value: 'first'},
{text: 'Second Option', value: 'second'},
{text: 'Third Option', value: 'third'}
]
},
{
xtype: 'textfield'
}
]
}
And I receive the configuration from the server, I understand the view like a store of different fields, and from the controller, it should add only fields specified in the json object.
How to create this dynamically following MVC concept?
Thank you
I assume that you have all the fields in the auxiliaryGroups.fields array.
After loading the form data from AJAX you can do it like this in your success call.
succses:function(response){
var response = Ext.decode(response.responseText);
var fields = response.auxiliaryGroups.fields;
var form = Ext.create("Ext.form.Panel",{
// here your form configuration.
cls:"xyz"
});
Ext.Array.forEach(fields,function(field){
var formField = {
xtype: field.type,
label: field.name,
name: field.id
};
form.add(formField);
});
Ext.Viewport.add(form);
form.show();
}
Based on my comment on your question, my idea about dynamic form generation is using ExtJS syntax to load form definition would be something like the code below; of course it would be extended and the data can be loaded from the server.
Ext.require([
'Ext.form.*'
]);
Ext.onReady(function() {
var data = [{
fieldLabel: 'First Name',
name: 'first',
allowBlank: false
}, {
fieldLabel: 'Last Name',
name: 'last'
}, {
fieldLabel: 'Company',
name: 'company'
}, {
fieldLabel: 'Email',
name: 'email',
vtype: 'email'
}, {
xtype: 'timefield',
fieldLabel: 'Time',
name: 'time',
minValue: '8:00am',
maxValue: '6:00pm'
}];
var form = Ext.create('Ext.form.Panel', {
frame: true,
title: 'Simple Form',
bodyStyle: 'padding:5px 5px 0',
width: 350,
fieldDefaults: {
msgTarget: 'side',
labelWidth: 75
},
defaultType: 'textfield',
defaults: {
anchor: '100%'
}
});
form.add(data);
form.render(document.body);
});
update:
When you create a view in run-time, communication between view and controller might be problematic because the controller doesn't know anything about the view. considering that the controller is responsible for initializing the view with appropriate data and handling view's events, data binding mechanism in ExtJS can solve the first part (initializing the view) which is described at View Models and Data Binding, the second part (handling view's events) can be solved with general methods in the controller, every element in the view should send its event to some specific methods and the methods based on the parameters should decide what to do.
This approach makes your methods in the controller a little fat and complicated that is the price of having dynamic form.
It is worth to mention that EXTJS raises different events in the life cycle of controllers and views and you should take benefit of them to manage your dynamic form.
I don't know about Touch, but in ExtJS, I usually do it by using the add function of a fieldset. You just loop through all your records, and create the fields on the fly.
var field = Ext.create('Ext.form.field.Text'); //or Ext.form.field.Date or a number field, whatever your back end returns.
Then set correct config options on field then
formFieldset.add(field);

Refresh Kendo UI grid data by reading a variable

Grid reads data from a javascript variable.
$("#grid").kendoGrid({
dataSource: {
type: "text",
data: jsvar,
schema: {
model: {
fields: {
id: {type: "string", editable: false},
name: {type: "string"}
}
}
},
pageSize: 20
},
pageable: {
input: true,
numeric: true
},
//toolbar: [{text: "Add"}],
columns: [
{command: [{text: "Edit", click: showDetailse}, {text: "View", click: viewoneitm}], title: " ", width: "170px"},
]
});
Then I change value of this variable jsvar with ajax and wait for ajax response and after that when I refresh grid with
jQuery("#grid").data("kendoGrid").dataSource.read();
jQuery("#grid").data("kendoGrid").refresh();
The grid is not repopulated with new data and old data stays in grid. Please tell me how to refresh grid data.
This worked fine and grid used to refresh perfectly untill I proviced static data, but after I used ajax and then 'refresh' it failed to update
If jsvar contains an array, the Kendo data source will create a model for each array item, so if you modify the original array, it won't change the DataSource. If you want to change the data, you should do it like this:
grid.dataSource.data(jsvar);

Unable to load store data in EXTJS Simplestore using JavaScript

I am trying to re-load data into the Store which is further used by a GridPanel. My code goes like:
Ext.onReady(function(){
myData = [
['document','listsk','123','','','rat'],
['hiiiii','himself','rest','','','lap']
];
// create the data store
store = new Ext.data.SimpleStore({
fields: [
{name: 'cat'},
{name: 'desc'},
{name: 'edcsId'},
{name: 'transformedEDCSUrl'},
{name: 'transformedFormatsUrl'},
{name: 'lineNotes'}
]
});
store.loadData(myData);
// create the Grid
grid = new Ext.grid.GridPanel({
store: store,
columns: [
{header: "<b>Category</b>", sortable: true, dataIndex: 'cat'},
{header: "<b>Description or Document Title</b>", sortable: true, dataIndex: 'desc'},
{header: "<b>EDCS ID #</b>", sortable: true, renderer: renderEDCSUrl, dataIndex: 'edcsId'}
{header: "<b>URLs to Formats</b>", renderer: renderFormatsUrl},
{id: 'lineNotes', header: "<b>Line Notes</b>", sortable: true, dataIndex: 'lineNotes'}
],
viewConfig: {
forceFit: true
},
autoExpandColumn: 'lineNotes',
stripeRows: true,
collapsible: true
})
reload = function refreshGrid(data){
store.loadData(data);
}
})
The mydata variable as seen by Firebug is:
[
['document','listsk','123','','','rat'],
['hiiiii','himself','rest','','','lap']
]
And the data variable in the javascript function refreshGrid is also same:
[
['document','listsk','123','','','rat'],
['hiiiii','himself','rest','','','lap']
]
I am invoking the function refreshGrid as follow:
function load(response) {
reload(response.substring(response.indexOf('myData') + 9,
response.indexOf('function renderABC') - 2));
}
To me it looks like a JSON parsing issue as data is coming fine from backend. Which is the best way to parse JSON string coming from backend. The behaviour with javascript invcation of store.loadData is that each character in the data variable is treated as separate row in the Grid as shown below:
Looks like you are providing an array of strings to the store instead of array of arrays as it expects.
As a result, store treats each value of an array(string actually) as an array. As soon as strings support referencing by index(at least in non-IE browsers), you get the behavior described.
For all who face this problem, a quick wayout is eval function and otherwise use some library for JSON.

ExtJS grid filters: how can I load 'list' filter options from external json?

I have a ExtJS (4.0) grid and it works fine. Now I want it to advance it a bit by adding filters to it. I want users to be able to filter items by the status.
I have created the following store:
var status_store = Ext.create('Ext.data.Store', {
model: 'Statuses',
proxy: {
type: 'ajax',
url: '/json/statuses/',
reader: 'json'
}
});
and I can see it loads, /json/statuses/ will return the following json object:
[
{
"name": "OK",
"isActive": true
},
{
"name": "Outdated",
"isActive": true
},
{
"name": "New",
"isActive": true
}
]
Now I define the filters:
var filters = {
ftype: 'filters',
encode: encode,
local: local,
filters: [{
type: 'list',
dataIndex: 'name',
store: 'status_store',
labelField: 'name'
}]
};
and add the filter to my column definition:
{text: 'Status', width: 120, dataIndex: 'status', sortable: true, filterable: true, filter: {type: 'list'}},
What happens is I get the following error when the grid loads:
Uncaught TypeError: Object json has no method 'read' (ext-all-debug.js:25702)
and when I click on the column header for the menu:
Uncaught TypeError: Object status_store has no method 'on' (ListMenu.js:69)
How can I fix this or am I doing something conceptually wrong?
Here is the full quote of my code just in case: http://pastebin.com/SNn6gFJz
Thanks for Diagnosing the problem. The 4.1 fix is this modify ListMenu.js
in the else part of the constructor
replace
me.store.on('load', me.onLoad, me);
with
// add a listener to the store object
var storeObject = Ext.StoreMgr.lookup(me.store);
storeObject.on('load', me.onLoad, me);
me.store = storeObject;
filters: [{
type: 'list',
dataIndex: 'name',
store: 'status_store',
labelField: 'name' ,
options:[a,b]
}]
You also have to give the options in list filters.
I was having a similar problem. I followed the #jd comment on the other answer here but the options menu just said "loading...". I resolved it with a bit of a hack here.

Categories

Resources