Clicking a column header displays jqgrid in ascending order - java

Currently i am working in java jqgrid I want to display the sorted grid after clicking of a column header.I already used onsortcol.but it is not working .her is my code.onsort col function is in active but it doesnt performs sorting.thanks in advance
CODE:
jq(function() {
var base = "<%=request.getContextPath()%>";
var records = -1;
jq("#grid").jqGrid({
url:base+'/admin/adminusermanagecrud.htm',
datatype: 'json',
mtype: 'GET',
colNames:['', 'Name','Employee ID','User Name','Mobile','City','State','Is Active','Created Date','Role','Bank Name'],
colModel:[
{name:'id',index:'id', width:55,editable:false,hidden:true},
{name:'adminName',index:'adminName', width:175,editable:true,sortable:true, editrules:{edithidden:true,required:false}, editoptions:{size:25,readonly:false,disabled:false},search:false},
{name:'adminEmployeeId',index:'adminEmployeeId', width:175,editable:true, editrules:{edithidden:true,required:false}, editoptions:{size:25,readonly:true,disabled:false},search:true},
{name:'adminuserName',index:'adminuserName', width:175,editable:true, editrules:{edithidden:false,required:false}, editoptions:{size:25,readonly:false,disabled:false},search:true},
{name:'mobile',index:'mobile', width:175,editable:true, editrules:{edithidden:false,required:false}, editoptions:{size:25,disabled:false},search:true},
{name:'city',index:'city', width:175,editable:true, editrules:{edithidden:true,required:false}, editoptions:{size:25,disabled:true},search:true},
{name:'state',index:'state', width:175,editable:true, editrules:{edithidden:true,required:false}, editoptions:{size:25,disabled:true},search:true},
{width:165,formatter:linkFormat,editable:true,edittype:'select',editrules:{edithidden:true,required:false}, editoptions:{value:"0:Activate;1:De-Activate",size:25,disabled:false,multiple:false},search:false},
{name:'createDate',index:'createDate',width:185,editable:true, editrules:{edithidden:true,required:false}, editoptions:{size:25,disabled:true},search:false},
{name:'role',index:'role',width:175,editable:true,editrules:{edithidden:true,required:false},editoptions:{size:25,disabled:true},search:false},
{name:'bankName',index:'bankName',width:175,editable:true,editrules:{edithidden:true,required:false},editoptions:{size:25,disabled:true},search:false}
],
postData:{
},
loadError:function(xhr,status,error)
{
var base = "<%=request.getContextPath()%>";
alert(status);
if(xhr.status == '403' || xhr.status == '401' || status == 'parsererror')
{
window.location.href = base+"/login.htm";
}
},
rowNum:5,
//rowList:[5,10,15,20],
height: 150,
//width:750,
autowidth: true,
rownumbers: true,
pager: '#pager',
sortname: 'adminName',
scrollrows:true,
viewrecords: true,
sortorder: "asc",
caption:"Admin Users Summary",
onSortCol: function (index, columnIndex, sortOrder) {
alert(index);
return 'stop';
},
cellEdit: false,
emptyrecords: "Search returned no results",
loadonce: false,
loadComplete: function()
{
},
jsonReader : {
root: function(obj)
{
if(obj.status == false)
{
window.location.href = base+"/login.htm";
}
else
{
records = obj.records;
return obj.rows;
}
},
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "cell",
id: "id"
},
editurl:base+"/admin/edit.htm"
});
jq("#grid").navGrid('#pager',
{edit:false,add:false,del:false,search:true,excel:true},
{ },
{ },
{ },
{
sopt:['eq','cn', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: false,
closeAfterSearch: true
}
);
jq("#btnFilter").click(function()
{
jq("#grid").jqGrid('searchGrid',
{
multipleSearch: false,
sopt:['eq']
}
);
});
});

Inside your controller you would need to handle the sorting. Something similar to
var pagedQuery = filteredQuery.OrderBy(sidx + " " + sord).Skip((page - 1) * rows).Take(rows);
where you actually sort your dataset and return it to jqGrid.

Related

how to change values in jqgrid pager

Senior Developer. I am a new developer and I am not sure about jqgrid.
Thank you very much for your help.
I am concerned about performance degradation when querying large amounts of data in jqgrid. So we only retrieve the data from the DB as much as the rowNum select Box value, and the total count of the data together with the number.
I want to change the values ​​of the pager according to the response
data after querying the condition. (pager value of jqgrid - total,
records...).
The structure of the server response object is
data: {
page: {
totalRowCount,
currentPage,
displayRowCount,
totalPage
},
fileInfoDtoList
}
That's it.
The totalRowCount and fileInfoDtoList sizes are not the same.
fileInfoDtoList contains only the data shown in the table of the current page.
totalRowCount is the total number of data that will be generated in the actual condition query.
I tried to change lastpage, records, total with setGridParam and also changed the internal value by assigning jsonReader to variable using getGridParam, but the actual pagerUI value did not change.
fileDataGrid.jqGrid({
url: setUrl(),
mtype: "GET",
datatype: "json",
colModel: [
{
label: 'date', name: 'baseDate',
formatter: function (cellValue, options, rowdata) {
let fixedValue = cellValue.substr(0, 4) + "-" +
cellValue.substr(4, 2) + "-" +
cellValue.substr(6, 2);
return $.fn.fmatter.call(this, "date", fixedValue, options, rowdata);
},
formatoptions: {
newformat: "Y-m-d"
}
, align: 'center'
},
{label: 'aa', name: 'diseaseName', align: 'right'},
{label: 'bb', name: 'fileName', align: 'right'},
{label: 'cc', name: 'fileSize', align: 'right'},
{label: 'dd', name: 'fileStateName', align: 'center'},
],
jsonReader: {
records: 'page.totalRowCount',
total:'page.totalPage',
root: 'fileInfoDtoList',
page: 'page.currentPage',
repeatitems: false
},
rowNum: 10,
viewrecords: true,
rownumbers: true,
emptyrecords: 'No Datas',
loadonce: false,
sortable: 'true',
pager: '#pager',
rowList: [10, 20, 30],
//paging event area
onPaging: function (pgButton) {
console.log(pgButton);
setTimeout(function () {
$.ajax({
url: setUrl(),
method: 'get',
success: function (data) {
console.log(data);
let rowNum = $("#fileDataCollectJqGrid").getGridParam('rowNum');
let currentPage = $("#fileDataCollectJqGrid").getGridParam('page');
let lastPage = $("#fileDataCollectJqGrid").getGridParam('lastpage');
let totalrows = $("#fileDataCollectJqGrid").getGridParam('totalrows');
console.log(" rowNum : " + rowNum + " currentPage : " + currentPage + " lastPage : " + lastPage + " totalrows : " + totalrows );
fileDataGrid.jqGrid('clearGridData');
let jsonReader = fileDataGrid.jqGrid('getGridParam', 'jsonReader');
console.log(jsonReader);
jsonReader.total = 999;
console.log(fileDataGrid.jqGrid('getGridParam', 'jsonReader'));
fileDataGrid.jqGrid("setGridParam", {
datatype: "local",
data: data.fileInfoDtoList,
lastpage: data.page.totalPage,
records: data.page.totalRowCount,
});
fileDataGrid.trigger('reloadGrid');
}
})
}, 0);
}
});
button event area
$("#searchButton").click(function () {
$.ajax({
url: setUrl(),
method: "get",
success: function (data) {
console.log(setUrl());
console.log(data);
let $fileDataCollectJqGrid = $('#fileDataCollectJqGrid');
$fileDataCollectJqGrid.jqGrid('clearGridData');
$fileDataCollectJqGrid.jqGrid("setGridParam", {
datatype: "local",
data: data.fileInfoDtoList,
totalRows: data.page.totalPage,
});
$fileDataCollectJqGrid.trigger('reloadGrid');
}
});
});
Initially, when I set jqgrid, it knows that the value of pager is set according to the setting value of jsonReader.
I tried to set the value of the pager after the condition query, but the value was not changed in the pagerUI part.
And I tried to change the total (total Page Count) and records (total Row Count) of the pager with setGridParam, but I changed the lastpage, totalrows, and so on. However, the total Row Count has changed by the size of the list.
fileDataGrid.jqGrid("setGridParam", {
datatype: "local",
data: data.fileInfoDtoList, <<--changed total (total Page Count) value of pager as this size of list.
lastpage: data.page.totalPage,
records: data.page.totalRowCount,
});
i solved problem myself!
just settled post Data as setGridParam when i call data request method.
i already set pager data in jsonReader. so i could solve my problem.
$('#fileDataCollectJqGrid').jqGrid('setGridParam', {
postData: {
collectId: "${collectId}",
baseDate: $('#dateInput').val(),
diseaseCode: $('#diseaseSelect').val(),
fileName: $('#fileNameInput').val(),
stateCode: $('#collectionStatus').val()
},
}).trigger('reloadGrid');

How to send data from controller which is acceptable format to Highstock?

I am new to Highstock, am not able to plot the graph.
I am sending an AJAX request to get the graph data.I am returning List of X-Axis Data, and List of Y-Axis Data, I also used Map but the values are coming like {1420051860000=101}, which is not acceptable format in Highstock.
$(document).ready(function(){
$.ajax({ url: 'getData',
dataType : 'json',
type: 'GET'
success: function (data) {
var xAxisdata= data.xAxisData;
var yAxisData=data.yAxisData;
//converting two arrays to two-dimesional array, It's not working
var jarray = [];
for (var i=0; i<xAxisdata.length && i<yAxisdata.length; i++){
jarray[i] = [xAxisdata[i], [yAxisdata[i]]];
}
//Getting these values for X and Y values
var xAxisdata=[1420051860000,1420052160000,1420052460000,1420052760000,1420053060000,....];
var yAxisdata=[100,110,112,113,110,112,111,110,115,116,114,114,110,114,112,113,110,....];
//Creates chart
var chart =new Highcharts.StockChart({
chart: {
renderTo: "container",
zoomType: 'x'
},
rangeSelector : {
selected : 1,
inputEnabled: $('#container').width() > 280
},
title : {
text : 'AAPL Stock Price'
},
credits: {
enabled: false
},
xAxis: {
title: {
text: 'Time'
},
type: 'datetime',
labels:{
formatter:function(){
return Highcharts.dateFormat('%H<br/>%d<br/>%m<br/>%Y',this.value);
}
},
},
yAxis: {
title: {
text: "Stock "
},
lineWidth: 1,
min:0,
gridLineWidth: 0
},
series : [{
name : 'AAPL',
showInLegend: true,
data : jarray,
marker : {
enabled : true,
radius : 3
}
}]
});
}
});
} );
And also facing issue with Months, in javaScript the months are starting from 0 to 11, But in java starts from 1. If the month is JAN-2014, it showing FEB-2014.
Suggest me the best way to plot the graph using JSON Response.
You were very close, there's just a little issue with the format of your array you've built.
Try to use
var jarray = [];
for (var i=0; i<xAxisdata.length && i<yAxisdata.length; i++){
jarray[i] = [xAxisdata[i], yAxisdata[i]];
}
Just remove the outer square brackets on [ yAxisdata[i] ]
Like in this jsFiddle

How to grab inner JSON map

Im trying to get specific values from the map.
I need to get value assigned to "leaguePoints", "tier", "rank", for
"queueType": "RANKED_SOLO_5x5" && "playerOrTeamName": "Invicterr".
I added code I try below.
I think I need to iterate entries:[], but I have no idea how to to this.
Im a total JSON newbie, and Java begginer.
Map:
"32303008": {
"queue": "RANKED_SOLO_5x5",
"name": "Sejuani's Berserkers",
"entries": [
{
"isHotStreak": false,
"isFreshBlood": false,
"leagueName": "Sejuani's Berserkers",
"miniSeries": {
"progress": "LWN",
"target": 2,
"losses": 1,
"timeLeftToPlayMillis": 0,
"wins": 1
},
"isVeteran": false,
"tier": "PLATINUM",
"lastPlayed": 0,
"playerOrTeamId": "21747474",
"leaguePoints": 100,
"rank": "V",
"isInactive": false,
"queueType": "RANKED_SOLO_5x5",
"playerOrTeamName": "sunchasee",
"wins": 127
},
{
"isHotStreak": false,
"isFreshBlood": false,
"leagueName": "Sejuani's Berserkers",
"isVeteran": false,
"tier": "PLATINUM",
"lastPlayed": 1389198358615,
"playerOrTeamId": "32303008",
"leaguePoints": 64,
"rank": "V",
"isInactive": false,
"queueType": "RANKED_SOLO_5x5",
"playerOrTeamName": "Invicterr",
"wins": 462
}
],
"tier": "PLATINUM"
}
My code:
for (Map.Entry<String, League> entry : leagues.entrySet())
{
try
{
if(Integer.parseInt(entry.getKey()) == 32303008)
{
System.out.println(entry.getKey() + "|" + entry.getValue());
}
}
catch(Exception e){}
}
I would recommend using something like JSON Simple. This will convert your JSON to a Java object that will be more simple to work with.
Pseudocode:
Map jsonMain = JSONParser.parse(myJSONSourceString);
Map numberedEntry = (Map)(jsonMain.get("3203008"));
List entries = (List)(numberedEntry.get("entries"));
for (int i = 0; i < entries.size(); i++) {
Map theEntry = (Map)(entries.get(0));
String queueType = (String)(theEntry.get("queueType"));
String playerOrTeamName = (String)(theEntry.get("playerOrTeamName"));
if (queueType.equals("RANKED_SOLO_5x5") && (playerOrTeamName.equals("Invicterr")) {
Number leaguePoints = (Number)(theEntry.get("leaguePoints"));
int leaguePointsValue = leaguePoints.intValue();
String tier = (String)(theEntry.get("tier"));
String rank = (String)(theEntry.get("rank"));
// Do something with the values
break;
}
}
The precise types and method names (and whether casting is needed) will depend on which JSON kit you use.

How to implement gwt-highcharts draggable data points in java?

I need to implement gwt-highcharts draggable data points in java, similar to what's done in js here:
http://jsfiddle.net/highcharts/AyUbx/ (code below)
I can't figure out how to do that in java from the gwt-highcharts javadocs. None of the mouse or click eventhandler documentation mentions how to capture drag info, or even how to capture mouse-up events, which combined with click events, would let me detect a drag action. I haven't found this anywhere else on the Web. Any help or examples would be greatly appreciated. I'm using GWT 2.5.1, and the latest versions of gwt-highcharts and jquery as of 2014-01-03. Thanks in advance. -Dan
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
animation: false,
zoomType: 'x'
},
xAxis: {
//categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
plotOptions: {
series: {
cursor: 'ns-resize',
point: {
events: {
drag: function(e) {
// Returning false stops the drag and drops. Example:
/*
if (e.newY > 300) {
this.y = 300;
return false;
}
*/
$('#drag').html(
'Dragging <b>' + this.series.name + '</b>, <b>' +
this.category + '</b> to <b>' +
Highcharts.numberFormat(e.newY, 2) + '</b>'
);
},
drop: function() {
$('#drop').html(
'In <b>' + this.series.name + '</b>, <b>' +
this.category + '</b> was set to <b>' +
Highcharts.numberFormat(this.y, 2) + '</b>'
);
}
}
},
stickyTracking: false
},
column: {
stacking: 'normal'
}
},
tooltip: {
yDecimals: 2
},
series: [{
data: [0, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
//draggableX: true,
draggableY: true,
dragMinY: 0,
type: 'column',
minPointLength: 2
}, {
data: [0, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4].reverse(),
draggableY: true,
dragMinY: 0,
type: 'column',
minPointLength: 2
}, {
data: [0, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
draggableY: true
}]
});

How to traverse a JSON file?

The JSON I have is mentioned below :-
{ head: {
link: [],
vars: [
"CompanyName",
"Company_Name",
"Foundation_URI",
"Foundation_Name",
"Latitude",
"Longitude"
] }, results: {
distinct: false,
ordered: true,
bindings: [
{
CompanyName: {
type: "uri",
value: "http://dbpedia.org/resource/United_Christian_Broadcasters"
},
Company_Name: {
type: "literal",
xml:lang: "en",
value: "United Christian Broadcasters"
},
Foundation_URI: {
type: "uri",
value: "http://dbpedia.org/resource/Christchurch"
},
Foundation_Name: {
type: "literal",
xml:lang: "en",
value: "Christchurch"
},
Latitude: {
type: "typed-literal",
datatype: "http://www.w3.org/2001/XMLSchema#float",
value: "-43.52999877929688"
},
Longitude: {
type: "typed-literal",
datatype: "http://www.w3.org/2001/XMLSchema#float",
value: "172.6202850341797"
}
},
{
CompanyName: {
type: "uri",
value: "http://dbpedia.org/resource/United_Christian_Broadcasters"
},
Company_Name: {
type: "literal",
xml:lang: "en",
value: "UCB Media"
},
Foundation_URI: {
type: "uri",
value: "http://dbpedia.org/resource/Christchurch"
},
Foundation_Name: {
type: "literal",
xml:lang: "en",
value: "Christchurch"
},
Latitude: {
type: "typed-literal",
datatype: "http://www.w3.org/2001/XMLSchema#float",
value: "-43.52999877929688"
},
Longitude: {
type: "typed-literal",
datatype: "http://www.w3.org/2001/XMLSchema#float",
value: "172.6202850341797"
}
},
{
CompanyName: {
type: "uri",
value: "http://dbpedia.org/resource/Kathmandu_%28company%29"
},
Company_Name: {
type: "literal",
xml:lang: "en",
value: "Kathmandu"
},
Foundation_URI: {
type: "uri",
value: "http://dbpedia.org/resource/Christchurch"
},
Foundation_Name: {
type: "literal",
xml:lang: "en",
value: "Christchurch"
},
Latitude: {
type: "typed-literal",
datatype: "http://www.w3.org/2001/XMLSchema#float",
value: "-43.52999877929688"
},
Longitude: {
type: "typed-literal",
datatype: "http://www.w3.org/2001/XMLSchema#float",
value: "172.6202850341797"
}
}
] } }
I want to know that how can I traverse this JSON to get the values of the appropriate variables as mentioned in the JSON file. I would like to know this with respect to JavaScript as well as Java. Please let me know how to traverse this JSON so as to get data easily.
This is not a JSON string but luckily a YAML standrd format.
You can use YAML library to transverse your jSON-like string
Here is a rather simple tree traversal routine:
function traverse(o) {
if( o instanceof Object ) {
for( key in o ) {
traverse(o[key]);
}
}
else if( o instanceof Array ) {
for( value in o ) {
traverse(value);
}
}
else {
console.log(o);
}
}
var q = { name : 'me', data : [ { a: 'a1', b: 'b1' }, { a: 'a2', b: 'b2'} ] };
traverse(q);
However, I think this is not quite what you're looking for. Please clarify and I will update my answer accordingly.
Following is a simple traversing of JSON object, this should help you undersatnd your JSON object normal traversing. Check the https://github.com/substack/js-traverse link for a detailed tutorial for complex traversing of any javascript object
<script language="javascript">
var emp = {"details" : [
{
"Name" : "Nitin1",
"Salary" : 10000,
"DOJ" : "16th Sept 2010"
}
,
{"Name" : "Abhijit2",
"Salary" : 5000,
"DOJ" : "15th Sept 2010"}
,
{"Name" : "Nilesh",
"Salary" : 50000,
"DOJ" : "10th Sept 2010"}
]
};
document.writeln("<table border='1'><tr><td>Name</td><td>Salary</td><td>DOJ</td></tr>");
var i=0;
for(i=0;i<emp.details.length; i++)
{
document.writeln("<tr><td>" + emp.details[i].Name + "</td>");
document.writeln("<td>" + emp.details[i].Salary +"</td>");
document.writeln("<td>" + emp.details[i].DOJ +"</td></tr>");
}
document.writeln("</table>");
</script>
If you only want to retrieve particular values - you do not need to traverse the entire JSON file.
This can be done in Javascript as follows:
Declared JSON variable:
var myJSONObject = {"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
};
Fetch a particular value:
myJSONObject.bindings[0].method // "newURI"
For a full reference you can go here.
I do not use Java myself, but XML.java (documentation available here) allows you to convert the JSON into XML. Parsing an XML is easy - you will find plenty of tutorials on it for Java such as:
http://www.seas.gwu.edu/~simhaweb/java/xml/xml.html
Cheers!

Categories