JQuery Grid-SubGrid for Parent-Child relation - json

I need some idea, about how to implement a subgrid in the following sceaniro.
The following is the json data that I want to display in the JQuery Grid and Subgrid.
Basically I am getting an object called "Contact" that has a collection called "actionSet".
{
"total" : "10",
"page" : "1",
"records" : "78",
"rows" : [ {
"comment" : null,
"givenName" : "Contact A",
"familyName" : "A",
"actionSet" : [ {
"actionID" : 1,
"actionDueDate" : "2012-12-08",
"actionNote" : "Action 1"
}, {
"actionID" : 2,
"actionDueDate" : "2012-12-08",
"actionNote" : "Action 2"
} ]
} ...]
}
I want eache Grid row to display the "Contact" and the subgris associated with the grid should display "actionSet" collection.
When a particular row in the Grid is selected, I do not want to make a server call to get the associated actions, as they are allready present in the "actionSet".
I have got the Grid working, displaying the "Contacts" nicely, but I get confused while implement the subgrid, as how to get the data for it, as its allready available in json.
jq(function() {
jq("#grid").jqGrid({
url:'/smallworks/project/getall.do',
datatype: 'json',
mtype: 'GET',
colNames:['Id', 'First Name', 'Last Name'],
colModel:[
{name:'id',index:'id', width:55,editable:false,editoptions: {readonly:true,size:10},hidden:true},
{name:'givenName',index:'givenName', width:100,editable:true, editrules:{required:true}, editoptions:{size:10}},
{name:'familyName',index:'familyName', width:100,editable:true, editrules:{required:true}, editoptions:{size:10}}
],
postData: {
},
rowNum:20,
rowList:[20,40,60],
height: 200,
autowidth: true,
rownumbers: true,
pager: '#pager',
sortname: 'id',
viewrecords: true,
sortorder: "asc",
caption:"Contacts",
emptyrecords: "Empty records",
loadonce: false,
loadComplete: function() {
},
Is this achievable?
Do I need to parse JSON data specially for the subgrid?
How can this be achieved?

I suggest that you save information from actionSet in an object which you can easy access later. For example you can use userData parameter and fill the userdata part of JSON data inside of beforeProcessing. The create subgrid you can follow the answer or another one.
The demo demonstrate the implementation approach:
It uses the following code
var mainGridPrefix = "s_";
$("#grid").jqGrid({
url: "Adofo.json",
datatype: "json",
colNames: ["First Name", "Last Name"],
colModel: [
{ name: "givenName" },
{ name: "familyName" }
],
cmTemplate: {width: 100, editable: true, editrules: {required: true},
editoptions: {size: 10}},
rowNum: 20,
rowList: [20, 40, 60],
pager: "#pager",
gridview: true,
caption: "Contacts",
rownumbers: true,
autoencode: true,
height: "100%",
idPrefix: mainGridPrefix,
subGrid: true,
jsonReader: { repeatitems: false },
beforeProcessing: function (data) {
var rows = data.rows, l = rows.length, i, item, subgrids = {};
for (i = 0; i < l; i++) {
item = rows[i];
if (item.actionSet) {
subgrids[item.id] = item.actionSet;
}
}
data.userdata = subgrids;
},
subGridRowExpanded: function (subgridDivId, rowId) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
pureRowId = $.jgrid.stripPref(mainGridPrefix, rowId),
subgrids = $(this).jqGrid("getGridParam", "userData");
$subgrid.appendTo("#" + $.jgrid.jqID(subgridDivId));
$subgrid.jqGrid({
datatype: "local",
data: subgrids[pureRowId],
colNames: ["Due Date", "Note"],
colModel: [
{ name: "actionDueDate", formatter: "date", sorttype: "date" },
{ name: "actionNote" }
],
sortname: "actionDueDate",
height: "100%",
rowNum: 10000,
autoencode: true,
autowidth: true,
jsonReader: { repeatitems: false, id: "actionID" },
gridview: true,
idPrefix: rowId + "_"
});
}
});
UPDATED: The JSON data used in the demo one can see below. I added id property which is required for jqGrid. I used actionID as the id of the subgrids:
{
"total": "10",
"page": "1",
"records": "78",
"rows": [
{
"id": 10,
"comment": null,
"givenName": "Contact A",
"familyName": "A",
"actionSet": [
{
"actionID": 1,
"actionDueDate": "2012-12-08",
"actionNote": "Action 1"
},
{
"actionID": 2,
"actionDueDate": "2012-12-09",
"actionNote": "Action 2"
}
]
},
{
"id": 20,
"comment": null,
"givenName": "Contact B",
"familyName": "B",
"actionSet": [
{
"actionID": 3,
"actionDueDate": "2012-12-11",
"actionNote": "Action 3"
},
{
"actionID": 4,
"actionDueDate": "2012-12-10",
"actionNote": "Action 4"
}
]
}
]
}

Related

AmStockChart by json did not display

I want to use AmChart and getting data for charts from MySQL by JSON.
But it display not things.
This is my js source:
<script type="text/javascript">
var chart2;
$(document).ready(function(){
$.getJSON("data", function (data) {
chart2.dataProvider = data;
chart2.dataDateFormat = "YYYY-DD-MM";
chart2.validateData();
});
});
var chart2 = AmCharts.makeChart("chartdiv2", {
type: "stock",
theme: "none",
pathToImages: "http://www.amcharts.com/lib/3/images/",
dataSets: [{
title: "Participants",
fieldMappings: [{
fromField: "student",
toField: "student"
}],
categoryField: "date"
}
],
dataDateFormat: "YYYY-MM-DD",
panels: [{
showCategoryAxis: false,
title: "Student",
percentHeight: 70,
stockGraphs: [{
id: "g1",
valueField: "student",
comparable: true,
compareField: "student",
balloonText: "[[title]]:<b>[[student]]</b>",
compareGraphBalloonText: "[[title]]:<b>[[student]]</b>"
}],
stockLegend: {
periodValueTextComparing: "[[percents.student.close]]%",
periodValueTextRegular: "[[value.close]]"
}
}],
chartScrollbarSettings: {
graph: "g1"
},
chartCursorSettings: {
valueBalloonsEnabled: true,
fullWidth: true,
cursorAlpha: 0.1,
valueLineBalloonEnabled: true,
valueLineEnabled: true,
valueLineAlpha: 0.5
},
periodSelector: {
position: "left",
periods: [{
period: "MM",
selected: true,
count: 1,
label: "1 month"
}, {
period: "YYYY",
count: 1,
label: "1 year"
}, {
period: "YTD",
label: "YTD"
}, {
period: "MAX",
label: "MAX"
}]
},
dataSetSelector: {
position: "left"
}
});
</script>
The json file output from data function
[{"date":"2011-01-10","student":"100"},{"date":"2012-02-11","student":"122"}]
Anyone know the solution please help. Thanks.
Try to parse your data,
For Eg,
$.getJSON("data", function (data) {
newData=JSON.parse(data);
chart2.dataProvider = newData;
chart2.dataDateFormat = "YYYY-DD-MM";
chart2.validateData();
});

Putting hyperlinks in JQGrid using jsonstring data

I have a json string which i am using to populate the jqgrid. in the string i have one element which is a hyperlink. the problem is that if i use this string then the grid does not load at all ! here is my code
var json = '{"total": "","page": "1","records": "","rows" : [{"id" :"1", "cell" :["Quantum of Solace","142456", "1234.89", "1234"]},{"id" :"2", "cell":["01/04/2013", "7741", "007997.66", "234"]},{"id" :"3", "cell":["06/08/2013", "78976", "2329.336", "234"]},{"id" :"4", "cell":["01/01/2012", "6678", "2154.22", "1234"]},]}';
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
datatype: 'jsonstring',
datastr:json,
colNames: ['Date', 'Account ', 'Amount', 'Code'],
colModel: [
{ name: 'adate', index: 'adate', width: 90, sorttype: 'date', datefmt: 'Y-m-d' },
{ name: 'account', index: 'account', width: 80, align: 'right', sorttype: 'int' },
{ name: 'amount', index: 'amount', width: 80, align: 'right', sorttype: 'float' },
{ name: 'code', index: 'code', width: 80, align: 'right', sorttype: 'int' }
],
pager: "#pager",
toppager: true,
rowNum: 10,
rowList: [10, 20, 30],
toolbar: [true, "top"],
sortorder: "desc",
viewrecords: true,
gridview: true,
imgpath: 'F:/profile/ProgramFiles/JQGrid/jquery-ui-1.10.3.custom/development-bundle/themes/redmond/images',
autoencode: true,
height: '100%',
caption: "My first grid"
}).navGrid('#pager', { edit: true, add: true, del: true, search: true, refresh: true, cloneToTop: true });
});
do i need to make a change in the colModel ? is that the reason why the grid does not load ? if i replace the link with random text, the grid works just fine.
please help, i really need to implement hyperlinks in the grid and i have to do it on the backend
First of all the usage of imgpath: 'F:/profile/...' options have the same effect like the usage of for example myName: 'user2334092'. Both options will be just ignored by jqGrid as unknown. I wrote you about it in my previous answer.
If you need to have a column of grid with hyperlink which data come from the server you can do the following. You need place all information which you need in the hyperlink as data. For example
[
{
"id": 10,
"href": "http://www.google.com",
"linktext": "Quantum of Solace",
"adate": "2012-12-15",
"account": 142456,
"amount": 1234.89,
"code": 1234
},
{
"id": 20,
"href": "https://stackoverflow.com/questions/17351495/",
"linktext": "Your question",
"adate": "2013-06-28",
"account": 7741,
"amount": 7997.66,
"code": 234
}
]
Then you can use for example
colNames: ["", "Date", "Account", "Amount", "Code"],
colModel: [
{ name: "linktext", width: 200, sortable: false, search: false,
formatter: function (cellValue, options, rowObject) {
return "<a href='" + rowObject.href + "'>" +
$.jgrid.htmlEncode(cellValue) + "</a>";
}},
{ name: "adate", width: 90, formatter: "date", sorttype: "date" },
{ name: "account", width: 80, formatter: "integer", sorttype: "int",
align: "right" },
{ name: "amount", width: 80, formatter: "number", sorttype: "float",
align: "right" },
{ name: "code", width: 80, formatter: "integer", sorttype: "int",
align: "right" }
]
to read and display the data. Usage the function $.jgrid.htmlEncode make you sure that you can currectly display any text in the link event textes like </td>foo "bar's which contains symbols having special meaning in HTML. You can remove formatter: "integer" and formatter: "integer" if you don't want to display numbers with thouthand separator and with decimal separator specified in jqGrid locale file (like from grid.locale-en.js). You can use formatoptions to specify the options of the formatters (see the documentation). The demo uses the code and it display the following results

Can't show the json Data in Treepanel in extjs 4

I am working on showing JSON data in EXTJS 4 TreePanel. But my tree is not showing any data . Please let me know where I am wrong. Let me post my codes below:
View Part: it has got the treepanel
xtype: 'treepanel',
title: 'Standard Geographies',
height: 250,
width: 310,
store: 'Data',
border: 1,
displayField: 'name',
useArrows: true,
rootVisible: true,
multiSelect: true,
preventHeader: true,
renderTo: Ext.getBody(),
columns: [{
xtype: 'treecolumn',
text: 'Standard Geographies',
flex: 1,
sortable: false,
//renderer : change,
dataIndex: 'name'
}],
Model Part: Using json data
Ext.define('TA.model.TAModel', {
extend: 'Ext.data.Model',
fields: ['name','typeId'],
//fields: ['abbr','type'],['name','typeId']
proxy: {
type: 'ajax',
url : 'data/StandardGeoTree.json',
actionMethods: {
read: 'POST'
},
reader: {
type: 'json',
root: 'geographyOptions'
},
}
});
Store Part: I hope all is ok in the store part
Ext.define('TA.store.Data', {
//extend: 'Ext.data.Store',
//model: 'TA.model.TAModel',
extend: 'Ext.data.TreeStore',
model: 'TA.model.TAModel',
autoSync: true,
autoLoad: true,
listeners: {
load:function(){
console.log('Schemes Data store loaded');
}
},
proxy: {
type: 'ajax',
//url : 'data/StandardGeoTree.json',
api: {
//read: 'data/StandardGeo.json',
read: 'data/StandardGeoTree.json',
//update: 'data/updateTradeArea.json'
},
reader: {
type: 'json',
root: 'root',
successProperty: 'success',
idProperty : 'typeId'
}
},
root : {
text: 'Root',
id: 'typeId',
expanded : true,
loaded : true,
children: []
}
});
JSON
{
"success": true,
"root" : [
{
"name": "001-USA",
"typeId" : "1",
"children":[
{"name": "USA", "typeId" : "1", "leaf":"true"},
{"name": "State", "typeId" : "2", "leaf":"true"},
{"name": "DMA", "typeId" : "3", "leaf":"true"},
{"name": "CSA", "typeId" : "4", "leaf":"true"},
]
}
]
}
the store configuration for tree component is actually doesn't need to be so complicated. for example simple store declaration below is enough:
var treestore = Ext.create('Ext.data.TreeStore', {
proxy: {
type: 'ajax',
url: 'data/StandardGeoTree.json'
}
});
then in your tree configuration set store: treestore and rootVisible: false
finally, the store expect json respond in this format:
[{
"text": "To Do",
"cls": "folder",
"expanded": true,
"children": [{
"text": "Go jogging",
"leaf": true
},{
"text": "Take a nap",
"leaf": true
},{
"text": "Climb Everest",
"leaf": true
}]
}]
In your JSON, your root property has to be similar to your children. So it's either "root" or "children", but not both. See this question for the full explanation.
So given you stick to:
reader: {
type: 'json',
root: 'root',
successProperty: 'success',
idProperty : 'typeId'
}
Your JSON should look like so:
{
"success": true,
"root" : [
{
"name": "001-USA",
"typeId" : "1",
"root":[
{"name": "USA", "typeId" : "1", "leaf":"true"},
{"name": "State", "typeId" : "2", "leaf":"true"},
{"name": "DMA", "typeId" : "3", "leaf":"true"},
{"name": "CSA", "typeId" : "4", "leaf":"true"},
]
}
]
}
Nothing worked as solution. So I had to write the below code part in my view which solved my problem. I am pasting the code part below:
var treeStore = Ext.StoreManager.lookup('Data');
treeStore.load();
But I want my store to be loaded automatically. Please let me know if you have any solution to automatically load the store.

jqGrid not displaying valid json

After reading most of the questions and trying to find an answer, I think I give up.
So the problem I'm having is just like what other people have been having, that is, jqGrid doesn't display the valid json received from a spring mvc servlet.
Here is my json:
{
"firstRecordIndex": 0,
"pageSize": 20,
"sortDirection": {
"name": "descending",
"code": 1
},
"sortCriterion": "id",
"pageNumber": 1,
"objectsPerPage": 20,
"fullListSize": 1,
"searchId": null,
"totalPages": 1,
"index": 0,
"list": [
{
"issueNumber": "ABC-6799",
"entryDate": 1345763592879,
"billingType": "Non-Billable",
"notes": "Hello",
"customer": "XYZ",
"id": 1,
"hours": 5,
"userName": "John Doe"
}
]
}
An here is my jqGrid:
jQuery(function(){
jQuery("#list").jqGrid({
url:"http://localhost:8080/worktime/timesheet.html?type=list&ajax=true",
datatype: "json",
colNames:["User", "Hours", "Date", "Billing Type", "Notes"],
colModel :[
{name:"userName", width:90, editable:false, jsonmap:"userName", editoptions:{readonly:true,size:10}},
{name:"hours", width:55, editable:true, jsonmap:"hours", editoptions:{size:10}},
{name:"entryDate", width:90, editable:true, jsonmap:"entryDate", formatter:"date", "formatoptions":{"srcformat":"m/d/Y", "newformat":"m/d/Y"},
editoptions:{size:12, dataInit:function(el){jQuery(el).datepicker({dateFormat:"m/d/y"});},defaultValue: "m/d/y"}
},
{name:"billingType", width:100, editable:true, jsonmap:"billingType", edittype:"select", editoptions:{value:"INV:Billable-Invoice;TSA:Billable-TSA;NON:Non-Billable;OH:Overhead"}},
{name:"notes", width:150, sortable:false, editable: true, jsonmap:"notes", edittype:"textarea", editoptions:{rows:"2",cols:"20"}}
],
pager: "#pager",
rowNum:10,
rowList:[10,20,30],
sortname: "entryDate",
sortorder: "asc",
jsonReader: {
root: "list",
total: "totalPages",
page: "pageNumber",
records: "fullListSize",
repeatitems: false,
id: "0"
},
caption: "Timesheet History",
viewrecords: true,
gridview: true,
});
What's the correct jqGrid configuration? I am using jqGrid 4.4.0 and jQuery 1.7.2. Your help is much appreciated. Thanks!!
Why do you have this: id: "0"?
Your jsonReader should probably be:
jsonReader: {
root: "list",
total: "totalPages",
page: "pageNumber",
records: "fullListSize",
repeatitems: false,
id: "id"
}

jqGrid JSON - Why doesn't jqGrid like this JSON? And can someone please provide the script and markup that will work with this string?

Here's the JSON:
{
"page": "1",
"total": "1",
"records": "2",
"rows": [
{
"Id": 3,
"FirstName": "Test",
"LastName": "Testerson",
"CustomerNumber": "1234",
"EmailAddress": "test#test.com",
"Subject": "Test1",
"OrderNumber": "4321",
"Comments": "This is a test"
},
{
"Id": 4,
"FirstName": "Test2",
"LastName": "Testerson2",
"CustomerNumber": "2222",
"EmailAddress": "test#test.com",
"Subject": "Test1",
"OrderNumber": "3333",
"Comments": "This is a test"
}
]
}
Here's my current script and markup (why isn't this working?):
<table id="list1"></table>
<div id="pager1"></div>
<script type="text/javascript">
function getData(pdata) {
var params = new Object();
params.page = pdata.page;
params.pageSize = pdata.rows;
params.sortIndex = pdata.sidx;
params.sortDirection = pdata.sord;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ScriptServices/PNScriptService.asmx/GetContactRequests",
data: JSON.stringify(params),
dataType: "json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#list1")[0];
thegrid.addJSONData(data.d);
}
},
error: function (data, textStatus) {
alert('An error has occured retrieving the data.');
}
});
}
$(document).ready(function () {
$("#list1").jqGrid({
datatype: function (pdata) {
getData(pdata);
},
jsonReader: {
page: "page",
total: "total",
records: "records",
root: "rows",
id: "Id",
repeatitems: false
},
colNames: ['Id', 'FirstName', 'LastName', 'CustomerNumber', 'EmailAddress', 'Subject', 'OrderNumber', 'Comments'],
colModel: [
{ name: 'Id', index: 'Id', width: 90 },
{ name: 'FirstName', index: 'FirstName', width: 100 },
{ name: 'LastName', index: 'LastName', width: 100 },
{ name: 'CustomerNumber', index: 'CustomerNumber', width: 80, align: "right" },
{ name: 'EmailAddress', index: 'EmailAddress', width: 100 },
{ name: 'Subject', index: 'Subject', width: 80 },
{ name: 'OrderNumber', index: 'OrderNumber', width: 80, align: "right" },
{ name: 'Comments', index: 'Comments', width: 250, sortable: false }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: $('#pager1'),
sortname: 'Id',
viewrecords: true,
sortorder: "desc",
caption: "Contact Requests"
});
});
</script>
btw: The JSON string above is the exact string returned by the script service. I can hit a break point in my script service and grab that string, and I can alert the string in the calling ajax script on success, and the strings are identical. So I know it's not the script service, and I know that that json string is being passed, as shown, into the jqGrid.
Your problem is that you user very very old template code for loading JSON data. If your server produce the JSON data which you posted you can simplify for code to the following.
In another answers you will find more code examples in case you use ASMX, which produce a litle other JSON code as you posted.
Thanks Oleg for the info, but it turned out to be the following:
thegrid.addJSONData(JSON.parse(data.d));
I needed to JSON.parse the data before passing it into the grid.