Creating a Dynamic Grid with ExtJS - javascript

I'm trying to make a Dynamic Grid class (where I do not know any information about the columns but they are given from the json response and the gird prepares itself accordingly). Here I have found exactly what I was looking for however it gives me an error:
me.model is undefined
me.setProxy(me.proxy || me.model.getProxy());
ext-all-debug.js (line 47323)
I have tried to add both proxy and model but I was not successful, I kept getting the same error.
Here is the ExtJS code that I'm working on:
// ExtJS 4.1
Ext.Loader.setConfig({
enabled: true
});
Ext.Loader.setPath('Ext.ux', '../extjs-4.1.0/examples/ux');
Ext.require([
'Ext.grid.*',
'Ext.data.*', ]);
Ext.define('DynamicGrid', {
extend: 'Ext.grid.GridPanel',
storeUrl: '',
enableColumnHide: true,
initComponent: function () {
var store = new Ext.data.Store({
url: this.storeUrl,
reader: new Ext.data.JsonReader(),
autoLoad: true,
scope: this,
listeners: {
scope: this,
metachange: function (store, meta) {
if (typeof (store.reader.jsonData.columns) === 'object') {
var columns = [];
/**
* Adding RowNumberer or setting selection model as CheckboxSelectionModel
* We need to add them before other columns to display first
*/
if (this.rowNumberer) {
columns.push(new Ext.grid.RowNumberer());
}
if (this.checkboxSelModel) {
columns.push(new Ext.grid.CheckboxSelectionModel());
}
Ext.each(store.reader.jsonData.columns, function (column) {
columns.push(column);
}); // Set column model configuration
this.getColumnModel().setConfig(columns);
this.reconfigure(store, this.getColumnModel());
}
}
}
});
var config = {
title: 'Dynamic Columns',
viewConfig: {
emptyText: 'No rows to display'
},
loadMask: true,
border: false,
stripeRows: true,
store: store,
columns: []
}
Ext.apply(this, config);
Ext.apply(this.initialConfig, config);
DynamicGrid.superclass.initComponent.apply(this, arguments);
},
onRender: function (ct, position) {
this.colModel.defaultSortable = true;
DynamicGrid.superclass.onRender.call(this, ct, position);
}
});
Ext.onReady(function () {
Ext.QuickTips.init();
var grid = Ext.create('DynamicGrid', {
storeUrl: 'http://300.79.103.188/ApplicationJs/jsontest.json'
});
var depV = Ext.create('Ext.Viewport', {
title: 'Departman Tanımları',
layout: 'fit',
items: grid
}).show();
});
What I have to do inorder to make it run?

That is a pretty old post so you may have more workarounds coming soon, but that error is because you do not have a model config or fields config defined for your store. The model will also need to be defined dynamically if you want your grid created with json data alone.
As far as I know, the fields config is pretty forgiving, so you may be able to just set this with a maximum possible number of fields like 20 or 30 or so, but the field names would have to match with the json field names for it to be usable. I.e. if you use:
var store = new Ext.data.Store({
url: this.storeUrl,
reader: new Ext.data.JsonReader(),
fields: [
'column1',
'column2',
'column3',
'column4',
'column5',
// etc
],
Then your json data would need to come from the database like:
[{"column1":"data1", "column2":"data2", // etc
Another thing I've done in the past is to have a reference store loaded first which contained a record with the name and datatype for each of the dynamic fields (meta data). Then I iterated through this reference store and added a model field and the column definition at each iteration, then I loaded the grid's store which now had the correct data model defined and the grid would have the correct column defintion.
You may have do something like that if you don't want to make your database return generic column names as covered above, because I don't know how you will load the data into your grid store initially before you give it a data model to use.
UPDATE 13 Jun:
I haven't tried it yet, but I just came across this in the 4.1 docs (scroll down to the "Response MetaData" section in the intro). It describes using metaData in your json response to accomplish exactly what you are going for with a dynamic model and grid columns.
You would probably still have to do the iteration I described above once you process the metaData, but you can use it to cut out that additional request to get the meta data.
I suppose if your field configuration doesn't change with each request then it would be easier to simply to do the extra request at the beginning, but if you want something really dynamic this would do it.

NOTE : This is a duplicte to my response here : How do you create table columns and fields from json? (Dynamic Grid) . I just wanted address my final solution in all of the StackOverflow questions I used to solve this problem.
Stackoverflow is littered with questions very similar to this one. I worked through them all and did not find a definitive solution. However, most of the provided answers pointed me in the right direction. I'll give me best shot at putting all those suggestions together and making this clear for others:
Model: (Only shows 2 fields that will be in all JSON responses. Will still be overwritten)
Ext.define('RTS.model.TestsModel', {
extend: 'Ext.data.Model',
alias: 'model.TestsModel',
fields: [
{
name: 'poll_date'
},
{
name: 'poller'
}
]
});
Store:
Ext.define('RTS.store.TestsStore', {
extend: 'Ext.data.Store',
alias: 'store.TestsStore',
model: 'RTS.model.TestsModel',
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: false,
proxy : {
type : 'ajax',
url : 'tests.php',
reader : {
type : 'json',
root : 'tests',
successProperty : 'success'
}
},
storeId: 'tests-store'
}, cfg)]);
}
});
View: (The columns will be defined in each JSON response)
Ext.define('RTS.view.TestsView', {
extend: 'Ext.grid.Panel',
alias: 'widget.TestsView',
id: 'tests-view',
title: 'Tests',
emptyText: '',
store: 'TestsStore',
initComponent: function() {
var me = this;
Ext.applyIf(me, {
viewConfig: {
},
columns: [
]
});
me.callParent(arguments);
}
});
Controller: (The controller does all the work in forcing the view and model to change based on the JSON response).
Ext.define('RTS.controller.TestsController', {
extend: 'Ext.app.Controller',
alias: 'controller.TestsController',
stores: [
'TestsStore'
],
models: [
'TestsModel'
],
views: [
'TestsView'
],
init: function(application) {
// When store changes, trigger an event on grid
// to be handled in 'this.control'.
// NOTE : Ext JS does not allow control of
// non-component events.
// Ext JS 4.2 beta will allow the controller
// to detect non-component changes and handle them
var testsStore = this.getStore('TestsStore');
testsStore.on("metachange", metaChanged, this);
function metaChanged(store, meta) {
var grid = Ext.ComponentQuery.query('TestsView')[0];
grid.fireEvent('metaChanged', store, meta);
};
this.control({
"TestsView": {
metaChanged: this.handleStoreMetaChange
}
});
},
/**
* Will update the model with the metaData and
* will reconfigure the grid to use the
* new model and columns.
*/
handleStoreMetaChange: function(store, meta) {
var testsGrids = Ext.ComponentQuery.query('TestsView')[0];
testsGrids.reconfigure(store, meta.columns);
}
});
JSON Response:
Your json response must have the "metaData" property included. It should define the fields just as you would on a static model and the view that would normally be defined to show the fields.
{
"success": true,
"msg": "",
"metaData": {
"fields": [
{
"name": "poller"
},
{
"name": "poll_date"
},
{
"name": "PING",
"type": "int"
},
{
"name": "SNMP",
"type": "int"
},
{
"name": "TELNET",
"type": "int"
},
{
"name": "SSH",
"type": "int"
},
{
"name": "all_passed"
}
],
"columns": [
{
"dataIndex": "poller",
"flex": 1,
"sortable": false,
"hideable": false,
"text": "Poller"
},
{
"dataIndex": "poll_date",
"flex": 1,
"sortable": false,
"hideable": false,
"text": "Poll Date"
},
{
"dataIndex": "PING",
"flex": 1,
"sortable": false,
"hideable": false,
"text": "PING",
"renderer": "RenderFailedTests"
},
{
"dataIndex": "SNMP",
"flex": 1,
"sortable": false,
"hideable": false,
"text": "SNMP",
"renderer": "RenderFailedTests"
},
{
"dataIndex": "TELNET",
"flex": 1,
"sortable": false,
"hideable": false,
"text": "TELNET",
"renderer": "RenderFailedTests"
},
{
"dataIndex": "SSH",
"flex": 1,
"sortable": false,
"hideable": false,
"text": "SSH",
"renderer": "RenderFailedTests"
},
{
"dataIndex": "all_passed",
"flex": 1,
"sortable": false,
"hideable": false,
"text": "All Passed",
"renderer": "RenderFailedTests"
}
]
},
"tests": [
{
"poller": "CHI",
"poll_date": "2013-03-06",
"PING": "1",
"SNMP": "0",
"TELNET": "1",
"SSH": "0",
"all_passed": "0"
},
{
"poller": "DAL",
"poll_date": "2013-03-06",
"PING": "1",
"SNMP": "0",
"TELNET": "1",
"SSH": "0",
"all_passed": "0"
},
{
"poller": "CHI",
"poll_date": "2013-03-04",
"PING": "1",
"SNMP": "0",
"TELNET": "1",
"SSH": "0",
"all_passed": "0"
},
{
"poller": "DAL",
"poll_date": "2013-03-04",
"PING": "1",
"SNMP": "0",
"TELNET": "1",
"SSH": "0",
"all_passed": "0"
},
{
"poller": "CHI",
"poll_date": "2013-03-01",
"PING": "1",
"SNMP": "0",
"TELNET": "1",
"SSH": "0",
"all_passed": "0"
}
]
}

Related

ExtJS create elements dynamically based on store items

Is it possible to create some other elements except Ext.panel.Grid using store property?
For example. Lets say that I have a panel:
Ext.create('Ext.panel.Panel', {
layout: 'vbox',
scrollable: true,
items: [
myItemsFunction()
]
}));
And from the backend I get this response:
{
"rows": [
{
"CreateDateTime": "2015-02-09 14:05:46",
"Name": "de.txt",
"id": "1"
},
{
"CreateDateTime": "2015-02-09 14:05:46",
"Name": "en.txt",
"id": "2"
},
{
"CreateDateTime": "2015-02-09 14:05:46",
"Name": "it.txt",
"id": "3"
}]
}
which I load in the store:
var store_documents = Ext.create('Ext.data.Store', {
remoteSort: true,
remoteFilter: true,
proxy: {
type: 'ajax',
api: {
read: baseURL + '&SubFunc=Documents&Action=view',
},
reader: { type: 'json', rootProperty: 'rows', totalProperty: 'total' }
},
autoLoad: true
});
Now, lets say that I want to have download buttons for these three files (de.txt, en.txt, it.txt). How can I create them dynamically based on store items? I want to put it in this myItemsFunction() and show it in panel items (first block of code sample)?
Or a store is only possible to bind with Grid?
You can use ExtJs store without binding it to a grid, because Ext.data.Store has a proxy which act as ajax request when you call store.load().
So you can find this working example ExtJs Fiddle
the basic idea is to define a new panel class and to use initComponent() function to allow you to create dynamic items based on the data retrieved from the request
app.js
Ext.application({
name: 'Fiddle',
launch: function () {
var storeData = {};
let store = Ext.create('Ext.data.Store', {
storeId: 'myStoreId',
fields: ['id', 'name'],
proxy: {
type: 'ajax',
url: 'app/data.json',
reader: {
type: 'json',
rootProperty: 'rows'
}
}
});
store.load(function(){
storeData = this.getData().items;
Ext.create('Fiddle.MyPanel',{panelData:storeData});
});
}
});
app/MyPanel.js
Ext.define('Fiddle.MyPanel', {
extend: 'Ext.panel.Panel',
renderTo: Ext.getBody(),
title: 'Dynamic button creation',
width: 600,
height: 300,
initComponent: function () {
let panelItems = [];
//Creating items dynamicly
for (btn in this.panelData) {
let me = this;
panelItems.push(
Ext.create('Ext.button.Button', {
text:me.panelData[btn].data.Name
})
);
}
this.items = panelItems;
//must call this.callParent()
this.callParent();
}
})
app/data.json
{
"rows": [
{
"CreateDateTime": "2015-02-09 14:05:46",
"Name": "de.txt",
"id": "1"
},
{
"CreateDateTime": "2015-02-09 14:05:46",
"Name": "en.txt",
"id": "2"
},
{
"CreateDateTime": "2015-02-09 14:05:46",
"Name": "it.txt",
"id": "3"
}]
}
Define a controller for you panel;
create an event function for afterrender;
inside it, load your store;
pass a callback parameter to your store's load function, where you iterate over loaded data creating button components;
call this.getView().add(button) to add your buttons to your panel items attribute

FullCalendar scheduler update resource JSON object

I'm working with Rails and FullCalendar Scheduler and I want to be able to update the JSON object I give as resource when I add a new one.
Here is a simplified version of my calendar options:
fullcalendar-settings.js
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'promptResource, prev, next, today',
center: 'title',
right: 'agendaWeek, timelineDay'
},
customButtons: {
promptResource: {
text: '+ maker',
click: function() {
var name = prompt('Name');
if (name) {
$('#calendar').fullCalendar(
'addResource', { title: name }, true // scroll to the new source?
);
}
}
}
},
defaultView: 'timelineDay',
defaultDate: moment(),
editable: true,
resourceColumns: [
{
labelText: 'Client',
field: 'title'
}
],
resources: 'scheduler.json',
events: []
});
});
scheduler.json
[
{ "id": "1", "title": "LE" },
{ "id": "2", "title": "DB" },
{ "id": "3", "title": "VB" },
{ "id": "7", "title": "RL" }
]
Resources are loaded from 'scheduler.json' and I have a button with which you can add a new resource but it is for now only temporary and disappear on reload.
So my question is how can I update the JSON object within 'scheduler.json' when I add a new resource ?
Thanks in advance
You need to learn Jquery Ajax. And you need to read the documentation of FullCalendar. There is no other way. But, if you need a quick fix you can watch this screencast. This will meet your requirement for sure I am guessing.

Send more values via URL

I am using Datatable plug-in to print values from database.
I get results and it prints in table. Now I am having trouble with sending values to the other file. Values that I need to send are userID, all titles of column except for last title, and two other variables which contains date.
When I click on '', beside data that contains userId, I need to send "User, Work time, Additions, Business, Break" as well as two variables printed below.
Other two variables are:
var date1 = "2017-01-01";
var date2 = "2017-02-28";
$('#myData').DataTable( {
data: dataSet,
fixedHeader: true,
responsive: true,
"columns": [
{ title: "User", data: "ime"},
{ title: "Work time", data: "Rad" },
{ title: "Additions", data: "Privatno" },
{ title: "Business", data: "Poslovno" },
{ title: "Break", data: "Pauza" },
{
"title": '<i class="icon-file-plus"></i>',
"data": "userID",
"render": function (data) {
return '' + '<i class="icon-file-plus"></i>' + '';
}, "width": "1%",
}
]
,"columnDefs": [ { "defaultContent": "-", "targets": "_all" },{ className: "dt-body-center", "targets": [ 5 ] } ]
});
Any help or advice is appreciated, I am stuck here.

How do put the JSON into EXTJS Grid?

I have a search with 3 Comboboxes if they are selected, the selected valueid send them by $POST and then by AJAX to PHP.
PHP is building from the combobox id's a mysql query and sends it back as JSON.
(JSON is validated)
But my grid is not filled! how i put the filtered by id data in my grid?
My Button
buttons:[
{
text:'Search',
loadingText:'lädt',
handler:function () {
var form = Ext.getCmp('searchPanel').getForm();
form.submit(
{url: 'php/search.php'}
)
MY validated JSON
"getRoutedata": [
{
"RouteID": "3",
"Loadingpoint": "Hafencity",
"Postalcode": "20457",
"Containercity": "Uhlenhorst",
"Carrier": "Bre SO",
"Transportmodel": "Truck",
"Containersize": "40",
"Containertype": "Horizontal",
"Harbor": "Antwerpen",
"Price": "1000.00",
"Year": "2012",
"Misc": "test"
}
]
My Store
storePPT = new Ext.data.JsonStore({
url:'php/search.php',
storeId:'myStore',
root:'getRoutedata',
stateful:true,
idProperty:'RouteID',
fields:[
{name:'Carrier', type:'string', mapping:'Carrier'},
{name:'Containercity', type:'string', mapping:'Containercity'},
{name:'Containersize', type:'string', mapping:'Containersize'},
{name:'Containertype', type:'string', mapping:'Containertype'},
{name:'Harbor', type:'string', mapping:'Harbor'},
{name:'Loadingpoint', type:'string', mapping:'Loadingpoint'},
{name:'Misc', type:'string', mapping:'Misc'},
{name:'Postalcode', type:'string', mapping:'Postalcode'},
{name:'Price', type:'decimal', mapping:'Price'},
{name:'Transportmodel', type:'string', mapping:'Transportmodel'},
{name:'Year', type:'year', mapping:'Year'},
{name:'RouteID', type:'int', mapping:'RouteID'}
]
});
Big thanks for your help!
You need to have store that will hold parsed data from your JSON response and a grid that will display data from this store. like:
//call this function in ajax success
function loadJsonData() {
var myStore = Ext.create('Ext.data.JSONStore', {
fields: [
{name1: 'field_name1'},
{name2: 'field_name2'},
{name3: 'field_name3'}
],
data: jsonData
});
// create the Grid
var grid = Ext.create('Ext.grid.Panel', {
store: myStore,
stateful: true,
stateId: 'stateGrid',
columns: [ {
text : 'field_name1',
sortable : false,
dataIndex: 'field_name1' // add fields you want to display
}, ... ]
renderTo: 'table' // add other params as you want
});
};
Hope it helps

JSON Object for jqGrid subgrid

This is my 3rd question about JSON data for jqGrid's subgrid, till now I did not get a single comment. Please somebody help.
my 1st questionand the
2nd one
I am having trouble getting to know the json format to be used by a subgrid in jqGrid. In my 2nd question i asked about the format that I should be using for a particular scenario
for the given image
Is this the proper JSON String?
var myJSONObject = {
"list": [
{
"elementName": "TERM",
"attribute": [
{
"name": "information",
"firstValue": "Required fixes for AIX",
"secondValue": "Required fixes for AIX"
},
{
"name": "name",
"firstValue": "PHCO_34",
"secondValue": "PHCO_34"
},
{
"name": "version",
"firstValue": "1.0",
"secondValue": "2.0"
}
],
"isEqual": false,
"isPrasentinXml1": true,
"isPrasentinXml2": false
},
{
"elementName": "Asian-Core.ASX-JPN-MAN",
"attribute": [
{
"name": "information",
"firstValue": "Man",
"secondValue": "Man"
},
{
"name": "name",
"firstValue": "Asian-Core.ASX-JPN-MAN",
"secondValue": "Asian-Core.ASX-JPN-MAN"
},
{
"name": "version",
"firstValue": "B.11.23",
"secondValue": "B.11.23"
}
],
"isEqual": false,
"isPrasentinXml1": true,
"isPrasentinXml2": true
}
]
};
If yes, my 1st question this is where i reached so far
$('#compareContent').empty();
$('<div id="compareParentDiv" width="100%">')
.html('<table id="list2" cellspacing="0" cellpadding="0"></table>'+
'<div id="gridpager2"></div></div>')
.appendTo('#compareContent');
var grid = jQuery("#list2");
grid.jqGrid({
datastr : myJSONObject,
datatype: 'jsonstring',
colNames:['Name','Result1', 'Result2'],
colModel:[
{name:'elementName',index:'elementName', width:90},
{name:'isPrasentinXml1',index:'isPrasentinXml1', width:100},
{name:'isPrasentinXml2',index:'isPrasentinXml2', width:100},
],
pager : '#gridpager2',
rowNum:10,
scrollOffset:0,
height: 'auto',
autowidth:true,
viewrecords: true,
gridview: true,
jsonReader: { repeatitems : false, root:"list" },
subGrid: true,
/*subGridModel: [{
//subgrid columns names
name: ['Name', 'Version', 'Information'],
//subgrid columns widths
width: [200, 100, 100],
//subrig columns aligns
align: ['left', 'left', 'left']
}]*/
// define the icons in subgrid
subGridOptions: {
"plusicon" : "ui-icon-triangle-1-e",
"minusicon" : "ui-icon-triangle-1-s",
"openicon" : "ui-icon-arrowreturn-1-e",
//expand all rows on load
"expandOnLoad" : true
},
subGridRowExpanded: function(subgrid_id, row_id) {
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_t";
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
jQuery("#"+subgrid_table_id).jqGrid({
datastr : myJSONObject,
datatype: 'jsonstring',
colNames: ['Name','Value1','Value2'],
colModel: [
{name:"name",index:"name",width:90},
{name:"firstValue",index:"firstValue",width:100},
{name:"secondValue",index:"secondValue",width:100},
],
rowNum:20,
pager: pager_id,
sortname: 'name',
sortorder: "asc",
height: 'auto',
autowidth:true,
jsonReader: { repeatitems : false, root:"attribute" }
});
jQuery("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{edit:false,add:false,del:false})
}
});
grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false});
Any type of suggestions/comments/solutions are welcome. Thanks
My output
You code has small errors in the declaration of the myJSONObject variable and the code which create the contain of the div#compareContent should be fixed to
$('#compareContent').empty();
$('<div id="compareParentDiv" width="100%">'+
'<table id="list2" cellspacing="0" cellpadding="0"></table>'+
'<div id="gridpager2"></div></div>')
.appendTo('#compareContent');
Small other syntax errors are the trailing commas in the colModel: the comma before ']' should be removed.
Now to your main problem. You should change datastr : myJSONObject in the subgrid to something like
datastr : myJSONObject.list[0]
then the modified demo will show the data: see here.
One more problem which you has is the absent of ids in your data. You should modify the structure of the data to define the unique ids for very grid row and every subgrid row. You should take in the considerations that ids from the data will be used as id of <tr> elements and HTML don't permit to have id duplicates on one HTML page.
UPDATED: See here an example of modification of your JSON input and the jqGrid so that ids will be used.
a couple of suggestion that may/maynot workout
when using subgrid select the grid as
var mygrid = jQuery("#mygrid")[0];
replace
var grid = jQuery("#list2");
with
var grid = jQuery("#list2")[0];
Ref: http://www.trirand.com/blog/?page_id=393/help/2-questions-about-jqgrid-subgrid-and-jsonstring
also change your json to a valid json
{
"list": [
{
"elementName": "TERM",
"attribute": [
{
"name": "information",
"firstValue": "RequiredfixesforAIX",
"secondValue": "RequiredfixesforAIX"
},
{
"name": "name",
"firstValue": "PHCO_34",
"secondValue": "PHCO_34"
},
{
"name": "version",
"firstValue": "1.0",
"secondValue": "2.0"
}
],
"isEqual": false,
"isPrasentinXml1": true,
"isPrasentinXml2": false
}
]
}
verfified by www.jsonlint.com
you may find the following link useful
jqGrid with JSON data renders table as empty

Categories

Resources