Alter the data before displaying it in the grid - javascript

I have a jqGrid that is filled by a JSON request, the thing is that the request back to the server in base64 encoded data and I need to decode the data before assign it to the grid.
Basically I need something like this:
$( "#grid" ).jqGrid( {
datatype: "json",
colNames: ["id", "Num", "Name", "Code"],
colModel: [
{ name: "id", index: "id", width: 30, sortable: true, resizable: false },
{ name: "num", index: "num", width: 150, sortable: true, resizable: false },
{ name: "name", index: "name", width: 250, sortable: true, resizable: false },
{ name: "code", index: "code", width: 150, sortable: true, resizable: false },
],
multiselect: true,
width: "760",
height: "100%",
heightMetric: "%",
shrinkToFit: false,
rowNum: 20,
rowList: [20,30,60],
pager: "#pager",
sortname: "id",
viewrecords: true,
sortorder: "asc",
headertitles : true,
caption: "Loading...",
beforeProcessing: function(data){
data = decompress(data); // Like this
}
})

The callback function beforeProcessing is the correct place where you can implement all what you need. The exact implementation depends on the format of the data returned by the server. If one uses datatype: "json" then the data returned from the server are typically an object which is serializes as JSON string. jqGrid uses internally jQuery.ajax which automatically decode the JSON string and convert it back to object. So the input data parameter of beforeProcessing callback is the object returned from the server. If you don't use any additional jsonReader option of jqGrid then jqGrid wait the input data in the standard format described here. So you need just fill the expected properties of data object (rows, page, total and records) based on the input data returned from the server. You don't posted any example of the data returned from the server, so I could give you no more detailed examples.

Related

What's wrong with my dynamically built colModel in jqGrid?

So, I am using jqGrid and due to the nature of this project, I need to build out the colModel dynamically. Meaning, I need to build the model itself dynamically. I am retrieving data fine with my JSON call.
So, I build an array of objects and then assign that array to the colModel property. No errors, but the data doesn't show up.... I am doing something very similar with colNames and it works fine. Does anyone see what I am missing? I have worked on this yesterday afternoon and all morning today and can't find any reason it shouldn't work.
As you can see, it am assigning the siteVal array at the top of my code to the colModel property.
var siteVal = [{name: 'InvtId', index: 'InvtId', width: 20, editable: false, sortable: false, align: 'left', hidden: true}];
siteVal.push({name: 'Descr', index: 'Descr', width: 320, sortable: false, editable: false, align: 'left'});
siteId.forEach(function(site){
curSite = site.substr(0,1)+"Val";
siteVal.push({name: curSite, index:curSite, width: 20, editable: false, sortable: false, align: 'left', hidden: true});
})
siteVal.push({name: 'Qty', index: 'Qty', width: 100, editable: true, sortable: false, align: 'right', hidden: true});
var colData = ['', 'Description'];
colData = colData.concat(siteId);
colData = colData.concat('Quantity');
console.log(colData);
jQuery("#list3").jqGrid({
url: 'OrdersInput.php?do=getdelvprice&state=' + $("#State").val() + '&city=' + $("#City").val() + '&FType=' + $("#FType").val() + '&siteid=' + $("#Plant").val(),
datatype: 'json',
mtype: 'GET',
colNames: colData,
colModel: siteVal,
loadonce: true,
height: 525,
width: 605,
rowNum: 1000,
key: false,
cellEdit: true,
cellsubmit: 'clientArray',
gridComplete: function() {
$("#MsgDel2").html("");
}
});
In using console.log to see the array right after I build it, this is what I get.
{"name":"InvtId","index":"InvtId","width":20,"editable":false,"sortable":false,"align":"left","hidden":true},
{"name":"Descr","index":"Descr","width":320,"sortable":false,"editable":false,"align":"left"},
{"name":"TVal","index":"TVal","width":20,"editable":false,"sortable":false,"align":"left","hidden":true},
{"name":"MVal","index":"MVal","width":20,"editable":false,"sortable":false,"align":"left","hidden":true},
{"name":"PVal","index":"PVal","width":20,"editable":false,"sortable":false,"align":"left","hidden":true},
{"name":"DVal","index":"DVal","width":20,"editable":false,"sortable":false,"align":"left","hidden":true},
{"name":"WVal","index":"WVal","width":20,"editable":false,"sortable":false,"align":"left","hidden":true},
{"name":"BVal","index":"BVal","width":20,"editable":false,"sortable":false,"align":"left","hidden":true},
{"name":"Qty","index":"Qty","width":100,"editable":true,"sortable":false,"align":"right","hidden":true}
This looks exactly as I think it should look in that it completely mimics the existing code where the colModel is defined statically. The thing is this must be dynamic to account for future growth...
I feel like a real idiot..... I was copying text from another line of code and didn't realize that I had included the last attribute... hidden:true
So, of course it wasn't showing up as I was telling it not to show. Guess that is what I get for copying and pasting code.

jQGrid - "jpg1" instead of proper id number

I'm loading local file (I'm parsing csv file into json and then transfer the array to jqGrid). Table generated through jqGrid should allow user to modify, add and delete the data in the grid. Everything seemed to work perfectly until I wanted to add a row to my grid. One of the columns had a parameter key = true which is my id for the rows. When I try to add new row, the grid changes my id into jpg1. The others columns are fine. Below is the code I'm using:
$("#jqGrid").jqGrid({
datatype: "local",
data: myData,
editurl: "clientArray",
colModel: [
{
label: 'Kod',
name: 'Kod',
width: 60,
editable: true,
key: true,
sorttype: 'number'
},
{
label: 'Firma',
name: 'Firma',
width: 120,
editoptions:
{
size: 40,
sopt:['cn']
},
editable: true,
sorttype: 'string'
},
{
label: 'Adres',
name: 'Adres',
width: 80,
editoptions: {size: 40},
editable: true
},
{
label: 'Miasto',
name: 'Miasto',
width: 80,
editoptions:
{
size: 40,
sopt:['cn']
},
editable: true
}
],
height: 'auto',
autowidth: true,
shrinkToFit: false,
forceFit: false,
autoencode: true,
viewrecords: true,
caption: "Title",
pager: "#jqGridPager",
sortable: true,
ignoreCase: true,
sortname: 'Kod',
sortorder: 'asc',
rowNum: 5,
rowList: [5, 10, 20, "10000:All"],
ondblClickRow: function(rowid) {
$("#jqGrid").jqGrid('editGridRow', rowid,
{
editCaption: "The Edit Dialog",
zIndex:100,
recreateForm: true,
closeAfterEdit: true,
width: 900,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
});
}
});
$('#jqGrid').jqGrid('navGrid',"#jqGridPager",
{ edit: true, add: true, del: true, search: false, refresh: true, view: true, cloneToTop: true},
// options for the Edit Dialog
{
editCaption: "The Edit Dialog",
zIndex:100,
recreateForm: true,
closeAfterEdit: true,
reloadAfterSubmit: true,
width: 900,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
width: 900,
zIndex:100,
closeAfterAdd: true,
recreateForm: true,
reloadAfterSubmit: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dialog
delSettings,
// options for the Search Dialog
{
zIndex:100
},
// options for the View Dialog
{
width: '100%'
});
I'm attaching a screenshot that shows a problem:
Photo
The data I use is a file parsed into JSON array via Papaparse.js plugin.
EDIT:
I've added the test data if somebody would like to test the code.
var myData = [];
myData.push(
{
Kod: 1.1,
Firma: 'Hutchinson',
Adres: '5th Avenue',
Miasto: 'Wroclaw'
},
{
Kod: 2.1,
Firma: 'BMW',
Adres: '6th Avenue',
Miasto: 'Warsaw'
});
I will be grateful for any help.
If you need the grid only for local editing, you can consider just remove key: true property to solve the problem. It's the way, which I would recommend you. You can include id property in the input data which will be used as value of rowid (id of <tr> elements).
Alternatively you can change the block "options for the Add Dialog" to the following
// options for the Add Dialog
{
width: 900,
zIndex:100,
closeAfterAdd: true,
recreateForm: true,
reloadAfterSubmit: true,
onclickSubmit: function (options, postdata, frmoper) {
// save Kod in some other parameter
return {myKod: postdata.Kod};
},
afterSubmit: function (jqXHR,postdata, frmoper) {
// restore the correct value
postdata.Kod = postdata.myKod;
// inform jqGrid that it was not an error
return [true];
}
},
You still don't would be able to change the id of the row in the way.
By the way you wrote that you use jqGrid 4.7.1. I want remind you that jqGrid 4.7.0 is the last version which is free. It's the reason why I started free jqGrid project which still free. You can get it here (see readme and wiki).
The demo shows an example of the above code fixes using free jqGrid 4.8.

jqgrid rowobject value is undefined

I use the following code for bind the values in jqgrid.
And i create one link button for access the Particular Action Method.
I need to pass the firstcolumn value to the action method.
But ,If i use this Following href='#Url.Action("ViewApplicants", "HR")?JobsID="+rowObject[0]+" '.It show the undefined Value .How to solve this?
<div>
<table id="Jobtable"></table>
<div id="jQGridPager"></div>
<div id="dialog" title="View Job Detail"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#Jobtable").jqGrid({
url: '/HR/PassJsonJob/',
datatype: "json",
mtype: 'GET',
colNames: ['Job ID', 'Job Title', 'Job Experience', 'Job Location', 'ViewApplicants'],
colModel: [
{ name: 'JobsID', index: 'JobsID', width: 150, align: 'left', editable: true },
{ name: 'JobTitle', index: 'JobTitle', width: 150, align: 'left', editable: true },
{ name: 'JobExperience', index: 'JobExperience', width: 150, align: 'left', editable: true },
{ name: 'JobLocation', index: 'JobLocation', width: 150, align: 'left', editable: true },
{
name: 'ViewApplicants', index: 'ViewApplicants', width: 150, sortable: false,
formatter: function (cellvalue, options, rowObject) {
alert(rowObject)
return "<a href='#Url.Action("ViewApplicants", "HR")?JobsID="+rowObject[0]+"'>View Applicants</a>";
}
}
],
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
loadonce: true,
gridview: true,
pager: "#jQGridPager",
cellEdit: false,
rowNumbers: true,
width: 1000,
caption: 'Applied Jobs',
viewrecords: true
})
$('#Jobtable').jqGrid('navGrid', '#jQGridPager',
{
edit: true,
add: false,
del: false,
view: false,
search: false
});
});
</script>
It's important to know the format of the server response from the URL /HR/PassJsonJob/. The format of rowObject corresponds to the format of items from the server response. So it could be that rowObject.JobsID instead of rowObject[0] would correct way to access JobsID property. Because you use loadonce: true the format of rowObject could be rowObject[0] at the first load. Later, for example, at local paging or sorting of data, the format of rowObject will be object with JobsID property, so rowObject.JobsID will be correct.
So the usage of rowObject.JobsID or rowObject[0] || rowObject.JobsID could fix your problem.
One more option could be to use the property key: true in the definition of JobsID column in colModel. One can use the property only if JobsID contains unique values in every row. In the case jqGrid will use the value from JobsID column as rowid: the value of id attribute assigned to the rows (<tr> elements) of the grid. In the case one could use options.rowId to access the JobsID value.
UPDATED: One more option exists in free jqGrid fork, which I develop since the end of 2014. The 2-d parameter (options) of the custom formatter has the property rowData, which contains the same information like rowObject, but it has always object format. Thus it's safe to use options.rowData.JobsID instead of rowObject[0] || rowObject.JobsID. One don't need to use the 3-d parameter of the the custom formatter at all. Free jqGrid didn't changed the format of the 3-d parameter to have the best upwards compatibility to the previous versions of jqGrid.

jqGrid add local data via javascript object

My problem is the following :
- i'm using jqgrid to display local data
- this data is parsed from a webservice in several parts
- i get an array of object as data (can be changed)
- i try to add the new data parts by parts with addJSONData, no luck
- i also tried with setting the jqGrid parameter "data" to a merged array of the data parts, no luck
With some trys i get empty rows.
Using a formatter the rowObject is ok, but the cellValue is empty (undefined).
It seems that the colModel and the data structure are not "compatible".
I want to be able to add data to the grid in several parts.
The rows should be displayed sorted.
Here are the parameters :
{
caption: 'Villes',
data: [],
datatype: 'local',
colNames: ['Actions', 'Distance', 'Coordonnées', 'Nom', 'Joueur', 'Puissance', 'Alliance', 'Diplomatie', 'Brumes', 'Status'],
colModel: [
{name: 'actions', sortable: false, search: false, formatter: Shared.gridRowActions, width: 50},
{name: 'range', index: 'range', width: 60},
{name: 'coords', index: 'gps', sortable: false, search: false, formatter: function( cellValue, options, rowObject ){ return Shared.mapLink(cellValue); }, width: 90},
{name: 'city', index: 'city'},
{name: 'player', index: 'player'},
{name: 'might', index: 'might', align: 'right', defval: 0, formatter: function( cellValue, options, rowObject ){ return Shared.format(cellValue); }, width: 70},
{name: 'guild', index: 'guild'},
{name: 'diplomacy', index: 'diplomacy', formatter: function( cellValue, options, rowObject ){ return Shared.getDiplomacy(cellValue); }, width: 70},
{name: 'mist', index: 'mist', align: 'center', formatter: function( cellValue, options, rowObject ){ return cellValue === 1 ? 'Oui' : ''; }, width: 55},
{name: 'user', index: 'user', formatter: function( cellValue, options, rowObject ){ return Shared.userStatusLink(cellValue); }}
],
pager: '#pager-cities',
loadui: 'disable',
rowNum: 20,
rowList: [20, 50, 100],
sortname: 'range',
sortorder: 'asc',
altRows: true,
autowidth: true,
viewrecords: true,
gridview: true,
multiselect: true,
multiboxonly: true,
multikey: 'shiftKey'
}
And then the code for adding data to the grid.
var merged = [];
var $grid = $('#grid);
...
merged = merged.concat(cities);
$grid.jqGrid('setGridParam', {data: merged}).trigger('reloadGrid');
Also tried:
$grid[0].addJSONData( {page: 0, total: 0, records: cities.length, rows: cities} );
The data array is for exemple:
[
{"id":338591,"cell":[2,"338,591","140","15545536","Lord Patrice02200","","0","Patrice02200",0]},
{"id":339591,"cell":[2.24,"339,591","50","16300072","Lord mercedes9pd7e","","0","mercedes9pd7e",0]},
{"id":341591,"cell":[3.61,"341,591","727714","16330552","Lord Torkan","","0","Rizane",0]},
{"id":341592,"cell":[4.24,"341,592","490","10929616","Lord pulpfiction","","0","pietra",0]}
]
The only things i really need is the ability to load the data by parts and that the grid data are displayed sorted after each data add.
A working pager will be a bonus.
Your problem is that you have chosen very exotic format of data. The default format representation of the local data is array of objects with named properties. Additional property in the array items are expected id. You use another format so you have to add localReader parameter which describes the format of data
The demo
uses the same grid which you posted. I just added
localReader: {repeatitems: true}
and removed all formatters which code you not posted. The best way to fill the grid is to use data option with the input data. I added height: "auto" only for better look of the grid. So you will see

jqGrid not showing rows, only shows total number of rows

I'm having a problem that I can't sort it out.
Please take a look at this image first
As you can see, I have been able to request the JSON data from server. The pager shows that there were 4 records. But the records didn't shows in the table.
This is my javascript code
jQuery("#pickFlex66").jqGrid({
url: root + '<?=$mod?>' + '/listpicker',
datatype: "json",
altRows: true,
mtype: 'POST',
colNames:['Code','Company Name'],
colModel:[
{name:'company_code',index:'company_code', width:100},
{name:'company_name',index:'company_name', width:100}
],
rowNum:10,
width: 540,
height: 310,
rowList:[10,20,30],
pager: '#pagerFlex66',
sortname: 'company_code',
shrinkToFit: false,
viewrecords: true,
sortorder: "desc",
caption:"<?=lang("users_title")?>",
onSelectRow: function(id){
}
});
jQuery("#pickFlex66").jqGrid('navGrid','#pagerFlex66',{edit:false,add:false,del:false,search:false});
And here is my JSON data
{
"page": "1",
"total": 0,
"records": "4",
"rows": [{"id":"5","cell":["55-123","123"]},{"id":"3","cell":["123","IBM"]},{"id":"2","cell":["00000","BDO"]},{"id":"1","cell":["000-00","IT GROUP Inc "]}]
}
Is there a mistake in my javascript? Or maybe in my JSON data?
I agree with Briguy37 that the value "total": 0 is strange and of cause incorrect. Nevertheless jqGrid should do display all data.
I suppose that you have the problem in the part of your code which you not posted here. How you can see from the demo the code which you posted can do read and display the JSON data.
Here's a couple issues...haven't figured out why your results aren't getting populated yet, though:
Total in your returned JSON should be the number of pages. Because it is set to 0, that is why it is displaying 0. Also, you'll probably want to return rowCount as 10 in case you change the number of results per page.
You are missing a json reader, I had the exact same problem.
$("#list").jqGrid({
url : "my-json-table-action' />",
datatype: 'json',
jsonReader: {
root: 'gridModel',
id: 'idTT',
repeatitems: false,
},
resize: false,
hidegrid: false,
data: 'trabajosTerminales',
mtype: 'POST',
height: 'auto',
colNames:['No. de Registro', 'Título', 'Tipo', 'Periodo'],
colModel :[
{name:'numRegistro', index:'titulo', search: 'true', stype:'text', align:'center' searchrules:{required:true}, width:100 },
{name:'titulo', key:'true', index:'titulo', search: 'true', stype:'text', searchrules:{required:true}, width:800 },
{name:'tipo', key:'true', index:'tipo', search: 'true', stype:'text',align:'center', searchrules:{required:true}, width:100 },
{name:'periodo', key:'true', index:'titulo', search: 'true', stype:'text', searchrules:{required:true}, width:100 },
],
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
viewrecords: true,
gridview: true,
caption: 'Trabajos Terminales dirigidos',
});
jQuery("#list").navGrid('#pager',{edit:false,add:false,del:false});
});
Where the root element is the array that contains your data, in this case I'm returning my data in an array called 'gridModel', the id is not necessary. But you have to make sure to set the root element right, in your case it's called 'rows' instead 'gridModel'.

Categories

Resources