how to bind json for extjs grid - extjs

I have a simple data in mysql and want to populate that data in a ExtJS grid
My code
Ext.onReady(function() {
var proxy = new Ext.data.HttpProxy({
url: 'connectextjs.php'
});
var reader = new Ext.data.JsonReader([{
name: 'Employee_ID',
mapping: 'Employee_ID'
}, {
name: 'Department_ID'
}, {
name: 'Name'
}, {
name: 'Email'
}])
var store = new Ext.data.Store({
proxy: proxy,
reader: reader
});
store.load();
// create the grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: [{
header: "Employee_ID",
width: 90,
dataIndex: 'Employee_ID',
sortable: true
}, {
header: "Department_ID",
width: 90,
dataIndex: 'Department_ID',
sortable: true
}, {
header: "Name",
width: 90,
dataIndex: 'Name',
sortable: true
}, {
header: "Email",
width: 200,
dataIndex: 'Email',
sortable: true
}],
renderTo: 'example-grid',
width: 540,
height: 200
});
});
My problem is I can't load the data on the grid. Please help me I am new to ExtJS.

connectextjs.php should return the json formated data with Employee_ID,Deaprtment_ID ,Name and Email init. Namming Convention should be followed strictly.

You can set the data of the grid by using this method.
First, assign an id to your grid, like this:
itemId : 'myGrid';
Get the JSON loaded from your JSON call, like this:
Ext.Ajax.request({
url : 'connectextjs.php',
params : {
yourParam : 'yourParameters'
},
// --> success simply means your action has no errors
success : function (conn, response, options, eOpts){
var jsonResults = Ext.JSON.decode(conn.responseText);
// --> Now that you have your JsonResults Its time to set it to your grid
me.getView().down('#myGrid').setStore(jsonResults);
}
});

Related

Extjs 4 how to return xml data with additional information from server to extjs controller?

I hope someone helps me out.
I want to load my grid with xml file's data, locally.
I created model,store and grid. I load the store in render event of grid.
The problem is,
Store is loaded but the grid is still empty. I looked at the grid at console, and grids items contains the loaded data, but grid doesnt contain the data on the screen.
Here is the model
Ext.define('BTOM.model.test.test', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id', type: 'string' },
{ name: 'name', type: 'string' },
{ name: 'phone', type: 'string' }
]
});
Here is the store
Ext.define('BTOM.store.test.test', {
extend: 'Ext.data.Store',
model: 'BTOM.model.test.test',
autoLoad: false,
proxy: {
type: 'memory',
reader: {
type: 'xml',
root: 'users',
record: 'user'
}
}
});
And the grid
Ext.define('BTOM.view.test.test', {
extend: 'Ext.grid.Panel',
store: 'BTOM.store.test.test',
alias: 'widget.test',
title: 'Test',
initComponent: function () {
this.columns =
[
{ header: "Id", width: 120, dataIndex: 'id', sortable: false },
{ header: "Name", width: 180, dataIndex: 'name', sortable: false },
{ header: "Phone", width: 115, dataIndex: 'phone', sortable: false}
];
this.callParent(arguments);
},
});
And where I load the store is
render: function (grid, eOpts) {
var store = grid.getStore();
var data =
'<?xml version="1.0" encoding="utf-8"?>' +
'<users> ' +
'<user><id>1</id><name>Bll QASD</name><phone>333 2211</phone></user> ' +
'<user><id>2</id><name>Asd QWF</name><phone>444 2211</phone></user> ' +
'<user><id>3</id><name>Zas QWE</name><phone>555 2211</phone></user> ' +
'</users>';
var dataXml = (new DOMParser()).parseFromString(data, 'text/xml');
console.log(dataXml);
store.loadRawData(dataXml, true);
console.log(grid);
}
dataXML document is created without problem.
grid seems to contain the data (by firebug, I can see)
but datagrid is empty, doesnt show the data!
Ok, the error is that you are defining the store but not creating it.
So the grid just has the name of the store but it expects a store instance,
or is that some thing you have missed in the code snippet above.
I used the same code and here is a running example:
https://fiddle.sencha.com/#fiddle/oel

EXTJS 3.4 - Grouping gridpanel based on GeoExt.data.WMSCapabilitiesStore

I am trying to implement grouping to the gridpanel using grouping store and grouping view.
Basically I want to modify the example given in this link;
http://api.geoext.org/1.1/examples/wms-capabilities.html
It is using Geoext web mapping library developed on extjs framework.Here GeoExt.data.WMSCapabilitiesStore is the store used for data from a url in XML.
Sample working xml can be viewed here:
url for xml
I am modifying the code to group the resulted records based on for example, 'name'.
Some how I am not able to properly configure the grouping store.
Here is my code sample:
var store;
Ext.onReady(function() {
// create a new WMS capabilities store
store = new GeoExt.data.WMSCapabilitiesStore({
url: "data.xml"
});
// load the store with records derived from the doc at the above url
store.load();
store.on('load',function(store,records,opts){
console.log(store.getRange());
}); //show the array data in firebug console
var reader = new Ext.data.ArrayReader({
fields: [{name: 'title'},
{name: 'name'},
{name: 'queryable'},
{name: 'abstract'}
]});
var grpstore = new Ext.data.GroupingStore({
data: store,
autoLoad: true,
reader: reader,
sortInfo:{field: 'title', direction: "ASC"},
groupField:'name'
});
//SP
// create a grid to display records from the store
var grid = new Ext.grid.GridPanel({
title: "WMS Capabilities",
store: grpstore,
columns: [
{header: "Title", dataIndex: "title", sortable: true},
{header: "Name", dataIndex: "name", sortable: true},
{header: "Queryable", dataIndex: "queryable", sortable: true, width: 70},
{id: "description", header: "Description", dataIndex: "abstract"}
],
view: new Ext.grid.GroupingView({
forceFit:true,
groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
}),
frame:true,
width: 700,
height: 450,
collapsible: true,
animCollapse: false,
autoExpandColumn: "description",
listeners: {
rowdblclick: mapPreview
},
iconCls: 'icon-grid',
fbar : ['->', {
text:'Clear Grouping',
iconCls: 'icon-clear-group',
handler : function(){
store.clearGrouping();
}
}],
renderTo: "capgrid"
});
function mapPreview(grid, index) {
var record = grid.getStore().getAt(index);
var layer = record.getLayer().clone();
var win = new Ext.Window({
title: "Preview: " + record.get("title"),
width: 512,
height: 256,
layout: "fit",
items: [{
xtype: "gx_mappanel",
layers: [layer],
extent: record.get("llbbox")
}]
});
win.show();
}
});
I am getting the panel with group options in the columns but the grid is empty. I tried many options in the data input of grouping store, but could not make it work.
Is it good way to get the data from 'store' as array, and then read it again in grouping store? But I couldnt make it working.
store.getRange() is showing all the data in the firebug console, probably as an array. I tried it as per this post. How to then call this array as data in grouping store, if this is a good way of doing it.
Any lead on this would be very helpful
Thanks
Sajid
I was looking to do exactly the same thing. I found two things:
You can use the store.Each function to copy the data from the WMSCapabilitiesStore to the Grouping Store
This was the trouble - the loading of the store is asynchronous, so you have to use store.on to set up a callback function to populate the groupingStore once the WMSCapabilitiesStore is finished loading.
Here's the code:
store = new GeoExt.data.WMSCapabilitiesStore({
url: "data.xml"
});
store.load();
grpStore = new Ext.data.GroupingStore({
groupField: 'name',
sortInfo: {field: 'name', direction: 'ASC'},
groupOnSort: true
});
store.on('load', function(store, records, options)
{
store.each(function(eachItem) {
grpStore.add(eachItem);
});
});
var grid = new Ext.grid.GridPanel({
store: grpStore,
columns: [
{header: "Title", dataIndex: "title", sortable: true},
{header: "Name", dataIndex: "name", sortable: true},
{id: "description", header: "Description", dataIndex: "abstract"}
],
autoExpandColumn: "description",
height: 300,
width: 650,
view: new Ext.grid.GroupingView({
forcefit:true,
groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
})
});

Looping Json array in Rowexpander plugin

I have a grid which I would like to show extra information with RowExpander plugin. When user click the cross, the json array should available in extended row. I tried everything but didn't successed to show the expanded content.
When I click the cross, I can see json array in console which is working well. But, the array content does not available in template.
Could you please help me, what I am doing wrong?
JSON ARRAY ( normal grid data )
[{"FORM_ID":"1","SUPPLIER_NO":"678456","SUPPLIER_NAME":"PINAR UNLU MAMÜLLER","RECORD_DATE":"12.06.2012","DELIVERY_NO":"215554","GRAND_TOTAL":"573","DRIVER_NAME":"Oğuz Çelikdemir","LICENSE_PLATE":"34 OGZ 6520"},{"FORM_ID":"2","SUPPLIER_NO":"75655463","SUPPLIER_NAME":"PINAR ET VE ET ÜRÜNLERİ","RECORD_DATE":"15.06.2012","DELIVERY_NO":"215556","GRAND_TOTAL":"619","DRIVER_NAME":"Murat Kayın","LICENSE_PLATE":"34 NES 7896"},{"FORM_ID":"3","SUPPLIER_NO":"32645668","SUPPLIER_NAME":"ÜLKER BİSKÜVİ","RECORD_DATE":"19.06.2012","DELIVERY_NO":"4563657","GRAND_TOTAL":"657","DRIVER_NAME":"Metin Yılmaz","LICENSE_PLATE":"06 ANK 6500"}]
JSON ARRAY ( expanded content )
[{"PRODUCT_NAME":"İÇECEK","QUANTITY":"2.00","SAS":"100","UNIT_ID":"1","UNIT_PRICE":"34.92","TOTAL":"70"},{"PRODUCT_NAME":"ŞARKÜTERİ","QUANTITY":"4.00","SAS":"100","UNIT_ID":"1","UNIT_PRICE":"34.92","TOTAL":"140"},{"PRODUCT_NAME":"KURU GIDA","QUANTITY":"1.00","SAS":"250","UNIT_ID":"1","UNIT_PRICE":"34.92","TOTAL":"35"},{"PRODUCT_NAME":"DETERJAN","QUANTITY":"5.00","SAS":"100","UNIT_ID":"1","UNIT_PRICE":"34.92","TOTAL":"175"},{"PRODUCT_NAME":"MEYVE SEBZE ve ET","QUANTITY":"3.00","SAS":"250","UNIT_ID":"1","UNIT_PRICE":"34.92","TOTAL":"105"}]
EXTJS
var formStore = new Ext.data.JsonStore({
url: 'form-data.php',
root: 'fdata',
idProperty: 'FORM_ID',
remoteSort: true,
fields: ['FORM_ID', 'SUPPLIER_NO', 'SUPPLIER_NAME', 'RECORD_DATE', 'DELIVERY_NO', 'DRIVER_NAME', 'LICENSE_PLATE',
{ name: 'GRAND_TOTAL', type: 'float'}]
});
formStore.setDefaultSort('RECORD_DATE', 'asc');
var checkboxSel = new Ext.grid.CheckboxSelectionModel();
var rowExpander = new Ext.grid.RowExpander({});
rowExpander.on('beforeexpand', function(rowexpander, record, body, rowindex) {
Ext.Ajax.request({
url: 'form-details.php' + '?fid=' + record.get('FORM_ID'),
method: 'GET',
success: function ( result, request ) {
var jsonData = Ext.util.JSON.decode(result.responseText);
tpl.overwrite(body, jsonData);
},
failure: function ( result, request ) {
Ext.MessageBox.alert('Failed', result.responseText);
return false;
}
});
return true;
});
var tpl = new Ext.Template(
'<p>URUN ADI : {PRODUCT_NAME}</p><br/>',
'<p>TOPLAM : {QUANTITY}</p>'
);
Ext.onReady(function() {
var grid = new Ext.grid.GridPanel({
title: 'ME.117.10 - Hammaliye Formu',
store: formStore,
sm: checkboxSel,
columns: [
checkboxSel, rowExpander,
{ header: "ID",
width: 40,
dataIndex: 'FORM_ID',
sortable: false
},
{ header: "Satıcı No",
id: 'form-id',
dataIndex: 'SUPPLIER_NO',
width: 40,
sortable: false
},
{ header: "Satıcı Firma",
dataIndex: 'SUPPLIER_NAME',
width: 290,
sortable: true
},
{ header: "Kayıt Tarihi",
width: 80,
dataIndex: 'RECORD_DATE',
sortable: true
},
{ header: "İrsaliye No",
width: 80,
dataIndex: 'DELIVERY_NO',
sortable: false
},
{ header: "Tutar",
width: 80,
dataIndex: 'GRAND_TOTAL',
sortable: false
}
],
autoExpandColumn: 'form-id',
renderTo: document.getElementById('form-results'),
width: 750,
height: 500,
loadMask: true,
columnLines: true,
plugins: rowExpander
});
formStore.load();
});
I assume you're using ExtJS 3.x as that's what your coding reflects. If you need help doing it in ExtJS 3.x I cannot help you much, I'm more used to the ExtJS 4.x way of coding, so that's what I'll use to try to explain this.
I am working to implement a nested grid just like this and have just been through this procedure:
Basically you need to config your main grid with a rowexpander plugin, which you have already done (below is the way I did it):
plugins: [{
ptype: "rowexpander",
rowBodyTpl: ['<div id="SessionInstructionGridRow-{ClientSessionId}" ></div>']
}],
Then in your controller you will just have to set up an event to happen on expandbody which is a rowexpander event:
this.control({
'gridview' : {
expandbody : this.onGridExpandBody
}
});
And then finally you write your script to the <div> tag you created in rowexpander plugin template:
onGridExpandBody : function(rowNode, record, expandbody) {
var targetId = 'SessionInstructionGridRow-' + record.get('ClientSessionId');
if (Ext.getCmp(targetId + "_grid") == null) {
var sessionInstructionGrid = Ext.create('TS.view.client.SessionInstruction', {
renderTo: targetId,
id: targetId + "_grid"
});
rowNode.grid = sessionInstructionGrid;
sessionInstructionGrid.getEl().swallowEvent(['mouseover', 'mousedown', 'click', 'dblclick', 'onRowFocus']);
sessionInstructionGrid.fireEvent("bind", sessionInstructionGrid, { ClientSessionId: record.get('ClientSessionId') });
}
}
Read: Nested grid with extjs 4 for more info.

ExtJS Filters Feature Error

I am a novice in ExtJS and I am trying to include filters in ExTJS grid but I am getting an error like failed loading file "feature.filters". Below is my function for creating Grid and I am invoking this function from another HTML page.
function ExtJSGrid(tableId,headerInfo,data){
Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', 'http://vmxplambardi:19086/teamworks/script/extjs/examples/ux');
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.ux.grid.FiltersFeature',
'Ext.toolbar.Paging'
]);
var tableId=tableId+"-div";
var fields=[],columns=[],dataIndex='cell';
var filters = {
ftype: 'filters',
local:true,
filters: [{
type: 'string',
dataIndex: 'cell1'
}, {
type: 'string',
dataIndex: 'cell2'
}, {
type: 'string',
dataIndex: 'cell3'
}]
};
document.getElementById(tableId).innerHTML='';
for(var i=1;i<=headerInfo.length;i++)
{
var cellObj={},columnObj={};
cellObj.name=dataIndex+i;
fields.push(cellObj);
columnObj.text=headerInfo[i-1];
columnObj.dataIndex=dataIndex+i;
columns.push(columnObj);
}
var store = Ext.create('Ext.data.ArrayStore', {
fields:fields,
data: data
});
var grid = Ext.create('Ext.grid.Panel', {
store: store,
columns:columns,
width:'100%',
forceFit:true,
features: [filters],
renderTo: tableId
});
}
Please let me know if I am missing anything?
Javascript has no block level scope, so variables defined in the for loop are actually defined at the top of the function (hoisted) and survive the loops. So you are always overwrite the vars.
I've got it working like this:
var filters = {
ftype: 'filters',
// encode and local configuration options defined previously for easier reuse
encode: false, // json encode the filter query
local: true, // defaults to false (remote filtering)
// Filters are most naturally placed in the column definition, but can also be
// added here.
filters: [
{
type: 'boolean',
dataIndex: 'visible' //Just an example
}
]
};
var myFilterGrid = new Ext.create('Ext.ux.LiveSearchGridPanel', {
title: 'someTitle',
selType: 'cellmodel',
store: myStore,
columns:[
{
header: "Column1",
width: 90,
sortable: true,
dataIndex: 'INDEX1',
filterable: true, //<---
filter:{ //<---
type:'string'
}
},
....
{
header: "Another Column",
width: 85,
sortable: true,
dataIndex: 'INDEX2'
}],
features: [filters] //<---
});
And be sure to include
'Ext.ux.grid.FiltersFeature'
Hope this helps!

extjs grid: re-get data from server when click button

I am try to research Extjs- grid. I created a button to display grid when click it. My code like below:
function onDisplay() {
Ext.onReady(function () {
var proxy = new Ext.data.HttpProxy({
url: 'server.jsp'
});
var reader = new Ext.data.JsonReader({}, [{
name: 'bookId',
mapping: 'bookId'
}, {
name: 'bookName'
}])
var gridStore = new Ext.data.Store({
proxy: proxy,
reader: reader
});
gridStore.load();
cols = [{
header: "bookId",
width: 60,
dataIndex: 'bookId',
sortable: true
}, {
header: "bookName",
width: 60,
dataIndex: 'bookName',
sortable: true
}];
var firstGrid = new Ext.grid.GridPanel({
store: gridStore,
columns: cols,
renderTo: 'example-grid',
width: 540,
height: 200
});
});
}
But when i click button N times -> it is displayed N grids. I only want display one grid and after click button it will get data from server again.
Please help me.
Thank you
You might want to look at some of the ExtJS Grid examples. They have lots of information about rendering grids from a store, and creating toolbars (which may include refresh buttons, for example). After cleaning up your example code a bit, I've come up with this:
Ext.onReady(function(){
var proxy=new Ext.data.HttpProxy( {url:'server.jsp'});
var reader=new Ext.data.JsonReader({},[
{name: 'bookId', mapping: 'bookId'},
{name: 'bookName'}
])
var gridStore=new Ext.data.Store({
proxy:proxy,
reader:reader
autoLoad:true
});
cols= [
{header: "bookId", width: 60, dataIndex: 'bookId', sortable: true},
{header: "bookName", width: 60, dataIndex: 'bookName', sortable: true}
];
var firstGrid = new Ext.grid.GridPanel({
store : gridStore,
columns : cols,
renderTo :'example-grid',
width :540,
height :200
});
//this code should ensure that only the grid updates,
//rather than rendering a whole new grid each time
var button = Ext.Button({
renderTo: "ButtonContainerId",
listeners: {
'click': function() {
gridStore.load()
}
}
})
});

Resources