Just putting in a new grid, and everything seems to be working well, except for one thing. Using basic inline, it is sending a new incorrect key value for the column I have set with key: true. This is an auto-increment column in the database, so I just don't want to send any data for this column when ADDING, only for edit or delete is that required.
It is posting a parameter: row_id => jqg3 for the new key column and messing up my server script. So because adding the new row will auto-increment the row_id col, I don't need to send this.
How do I stop the jqGrid from sending this (row_id) index column value when saving a new added row?
free-jqgrid version is 4.14.0
$('#accts').jqGrid({
url:'/phpAJAX/Master/master_grid_v1.php',
editurl:'/phpAJAX/Master/master_grid_v1.php',
height: 'auto',
shrinkToFit: false,
width: 'auto',
datatype: 'xml',
mtype: 'POST',
postData:{
'arg1':'bol_acct'
},
colNames:[
'row_id',
'Customer',
'Trucker',
'Acct Num'
],
colModel:[
{name: 'row_id', hidden: true, key: true},
{name:'Customer', align: "center", editable: true},
{name: 'Trucker', align: "center"},
{name: 'Acct_Num', align: "center"}
],
sortname: 'Customer',
sortorder: 'desc',
viewrecords: true,
gridview: true,
caption: 'Bill of Lading Accounts',
rowNum: 10000,
pager:true
}).jqGrid('inlineNav', {
addParams: {
addRowParams: { extraparam: {'arg1':'bol_acct', 'oper':'add'} }
},
editParams: {
extraparam: {
'arg1':'bol_acct', 'oper':'edit'
}
}
})
One can use serializeSaveData callback of inline editing to modify the data, which will be send during inline editing. You can add serializeSaveData callback via
inlineEditing: {
keys: true,
extraparam: { arg1: "bol_acct" },
serializeSaveData: function (postData) {
var newPostData = $.extend(true, {}, postData);
if (newPostData.oper === "add") {
delete newPostData.id; // delete id parameter
}
return newPostData;
}
}
Related
Attempting to load data from server based off of multisearch/filters, but do sorting and paging on client. i have found a few posts that say to simply set the datatype back to the original value in the beforeSearch method.
i have attempted this and it does execute against the server and return the correct data. However, the second time i filter it seems to get the data from the server but then it gets wiped out on line 4429 in the jqgrid code shown below. Any idea on how to achieve this goal?
Ln 4429 : p.lastSelectedData = query.select();
grid definition:
$element
.jqGrid({
cmTemplate: { search: true, searchoptions: { attr: { placeholder: "filter..." }, clearSearch: true }, sortable: true, align: "center" },
colModel: [
{ name: "Id", key: true, hidden: true, searchoptions: { searchhidden: true, sopt: ["eq"] } },
{ name: "TransmissionId", label: "Transmission Id", searchoptions: { sopt: ["eq"] } },
{ name: "Name", label: "Name", searchoptions: { sopt: ["cn"] } }
],
datatype: "json",
loadonce: true,
height: "auto",
ignoreCase: true,
pager: $("#" + pagerId),
pgbuttons: true,
pginput: false,
rowList: [10, 25, 50],
rowNum: 10,
toppager: true,
url: "url here",
loadComplete: function (data) {
if (this.p.datatype === "json") {
setTimeout(function () {
$element.trigger("reloadGrid", [{ page: 1 }]);
}, 50);
}
return data;
},
viewrecords: true
})
.jqGrid("filterToolbar", {
autosearch: true,
defaultSearch: "cn",
beforeSearch: function () {
$element.setGridParam({ datatype: "json", page: 1 });
}
})
.jqGrid("navGrid", "#" + pagerId, {
edit: false,
add: false,
del: false,
refresh: false,
view: false,
cloneToTop: true
});
I have trimmed down the grid to try to verify it is not custom logic that is causing this issue. the grid does have multipleSearch on. but is not defined above.
If I understand correctly your question then you should use forceClientSorting: true in combination with loadonce: true. It force that the data loaded from the server will be sorted, filtered and paged locally directly after loading from the server. Thus you can remove loadComplete, which you use currently. See the answer for a demo.
Additionally, you can add searching property, where you include all options of filterToolbar and searchGrid:
searching: {
autosearch: true,
defaultSearch: "cn",
beforeSearch: function () {
var p = $(this).jqGrid("getGridParam"), // get reference to all parameters
filters = JSON.parse(p.postData.filters);
p.datatype = "json";
// one can here analyse filters, modify it or clear it as
p.postData.filters = "";
// one can set any other parameters, which will be sent to the server
// by using p.postData.param1 = "value1";
// which will sent param1=value1 to the server.
}
}
In general you can do the same inside your current beforeSearch too.
UPDATED: Probably you should use beforeProcessing callback additionally. beforeProcessing will be called directly after receiving the data from the server. Inside of the callback you can clean-up all p.postData.filters (to "") and p.search (change it from true to false). As the result jqGrid will not try to filter locally by postData.filters the data returned from the server.
I want this:
Without having to start like this:
But for some reason the data only shows up when I use "hiddengrid: true,"
I tried following this demo and was only able to get the example to work by adding "hiddengrid: true," like so:
<body>
<div class="center" id="overGrid">
<table id="jqGrid"></table>
<div id="jqGridPager"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#jqGrid").jqGrid({
url: 'api/codes',
editurl: 'api/codes',
colModel: [
{
label: "Edit Actions",
name: "actions",
width: 75,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: {}
}
},
{
label: 'Id',
name: 'id',
width: 150,
editable: true
},
{
label: 'Title',
name: 'title',
width: 100,
editable: true
},
{
label: 'Code',
name: 'code',
width: 100,
editable: true
},
{
label: 'Original Url',
name: 'originalUrl',
width: 200,
editable: true
}
],
align: 'center',
viewrecords: true,
rowList: [10, 20, 30],
width: 925,
height: 445,
rowNum: 20,
loadonce: true,
hiddengrid: true, // <-------------------- HERE
toppager: '#jqGridPager',
pager: '#jqGridPager',
caption: "Database"
}); jQuery("#jqGrid")
.navGrid('#pager', { edit: false, add: false, del: false, search: false })
.navButtonAdd('#pager', {
caption: "Add",
buttonicon: "ui-icon-add",
onClickButton: function () {
alert("Adding Row");
},
position: "last"
})
.navButtonAdd('#pager', {
caption: "Del",
buttonicon: "ui-icon-del",
onClickButton: function () {
alert("Deleting Row");
},
position: "last"
});
function fetchGridData() {
var gridArrayData = [];
// show loading message
$("#jqGrid")[0].grid.beginReq();
$.ajax({
url: 'api/codes',
mtype: 'POST',
datatype: 'JSON',
success: function (result) {
for (var i = 0; i < result.items.length; i++) {
var item = result.items[i];
gridArrayData.push({
id: item.id,
title: item.title,
code: item.code,
originalUrl: item.originalUrl,
});
}
// set the new data
$("#jqGrid").jqGrid('setGridParam', { data: gridArrayData });
// hide the show message
$("#jqGrid")[0].grid.endReq();
// refresh the grid
$("#jqGrid").trigger('reloadGrid');
}
});
}
fetchGridData();
});
</script>
</body>
Examples such as this don't seem to be working for me on their own so I keep having to reference other sources such as this that are much more complex and informative but possibly the reason for why I continue to have issues every step of the way.
Side Note
I should probably point out that I was only just recently introduced to jqGrid as a result of this question I asked about a week ago: " How can I separate my output using “onclick” and format the data to 20 per page?
"
I did a fairly decent job of documenting the steps that brought me to this point so it might be worth checking out for an in depth look as to what I am dealing with.
In short I am building an API in Asp.Net Core that sends and receives JSON data to my MongoDb database and then outputs the data to a single HTML page using jqGrid. So far I have created functioning Get, Post, Put, and Delete methods that return and send JSON data to my MongoDb database.
Update:
I have gone through the docs suggested by Tony Tomov and I understand their meaning. I just haven't the slightest clue to the solution to this problem. Everything I have thought to be a possible solution and tried from before and after I posted this question has given me a blank page without any errors.
Im trying to put some data into jqGrid and force it to be displayed in a treeview.
My problem is, the 6th item (cid=6) is not showing in the grid. The 4th item looks like it has some subitems, but expanding this branch shows nothing. The 6th item is nowhere to find in the tree (I suppose, I've defined it as subitem of cid4).
Here is a working example of this code http://jsfiddle.net/498jhxcg/
(my production code uses POST/AJAX/JSON, the example is changed to localdata. Grid is displayed in the same wrong way in both cases.)
Is the data in wrong format, or the jqgrid is wrong defined? (btw. changing parent_id to parentid did not helped.)
var myjsondata = '{"rows":[
{"cid":"1","name":"cat1","lvl":"0","parent_id":"null","isleaf":true,"expanded":false,"loaded":true},
{"cid":"2","name":"cat2","lvl":"0","parent_id":"null","isleaf":false,"expanded":false,"loaded":true},
{"cid":"3","name":"cat3","lvl":"1","parent_id":"2","isleaf":true,"expanded":false,"loaded":true},
{"cid":"7","name":"cat7","lvl":"1","parent_id":"2","isleaf":true,"expanded":false,"loaded":true},
{"cid":"4","name":"cat4","lvl":"0","parent_id":"null","isleaf":false,"expanded":false,"loaded":true},
{"cid":"6","name":"cat6","lvl":"1","parent_id":"4","isleaf":true,"expanded":false,"loaded":true},
{"cid":"5","name":"cat5","lvl":"0","parent_id":"null","isleaf":true,"expanded":false,"loaded":true}
],"records":7,"total":1}';
$('#jgtable').jqGrid({
ExpandColumn:'id',
datastr: myjsondata,
datatype: 'jsonstring',
colNames: [
'Id',
'Name',
'Parent id',
'isLeaf?',
],
colModel: [
{ index: 'cid', name: 'cid', width:"75px"},
{ index: 'name', name: 'name', width:"75px"},
{ index: 'parent_id', name: 'parent_id',width:"75px"},
{ index: 'isleaf', name: 'isleaf', width:"75px"},
],
pager: '#pager',
rowNum: 10,
rowList:[2, 10, 25, 50, ],
height: 'auto',
minHeight: '250px',
recordpos: 'right',
viewrecords: true,
gridview: false,
treeGrid: true,
treeGridModel : 'adjacency',
treedatatype: "local",
treeReader : {
level_field: "lvl",
parent_id_field: "parent_id",
leaf_field: "isleaf",
expanded_field: "expanded",
loaded_field: "loaded",
index_field: "cid",
},
jsonReader: {
repeatitems: false,
},
});
It seems to me that you should add key: true property to the definition of cid column. You can use alternatively (or to do both things) the option jsonReader: { id: "cid" }. In the case the value of cid property of input data will be interpreted as the id of the item and the value from parent_id will be correct.
see http://jsfiddle.net/OlegKi/498jhxcg/19/
I can't seem to get jqGrid pagination to work. It is not making a request when I click next/prev/reload or when I try to filter. As soon as I click any of those buttons, all of the records disappear.
This is the initial request that gets sent, so you can see that all of those parameters are being passed in.
https://www.xxxxxxx.com/getallorders?contactId=333&bucketId=444&_search=false&nd=1366982305621&rows=20&page=1&sidx=PKId&sord=desc
This returns proper number of records, and if I manually execute it and pass in let's say page=2 I do get proper set back. The problem seems to be that the request is not made.
jQuery("#grid").jqGrid({
url:'/GetAllOrders',
mtype: "GET",
datatype: "json",
jsonReader: {
root: "Rows",
page: "Page",
total: "Total",
records: "Records",
repeatitems: false,
userdata: "UserData",
id: "Id"
},
postData: {
contactId: currentUserId,
bucketId: currentBucketId
},
colNames:[
'Id',
'Cancel',
'Order #',
'Order Date',
'Bucket',
'Warehouse',
'Destination',
'Status',
'Tracking #',
'Transport By',
'Ordered By',
'Order Items'
],
colModel:[
{name:'Id',index:'Id', width:5, align:"center", hidden: true},
{name:'Cancel', index:'Cancel',width:80, align:"center", formatter: cancelLinkFormatter, search:false },
{name:'OrderNumber',index:'OrderNumber', width:80, align:"center"},
{name:'OrderDate',index:'OrderDate', width:140, align:'right'},
{name:'Bucket',index:'Bucket', width:180, align:"center", hidden: false},
{name:'Warehouse',index:'Warehouse', width:80, align:"center", hidden: true},
{name:'Destination',index:'Destination', width:150},
{name:'StatusCode', index:'StatusCode', width:100, align: 'center'},
{name:'TrackingNumber', index:'TrackingNumber', width:100, align: 'center'},
{name:'TransportCompany', index:'TransportCompany', width:100, align: 'center'},
{name:'OrderedBy', index:'OrderedBy', width:100, align: 'center'},
{name:'OrderItems', index:'OrderItems', width:100, align: 'center'}
],
viewrecords: true,
rowNum: 20,
autowidth: false,
width: 860,
height: 450,
rowList:[10,20,30,40,50],
pager: jQuery('#pager'),
sortname: 'Id',
align: 'center',
sortorder: "desc",
loadonce: false,
ignoreCase: true,
caption:"Orders"
}).navGrid('#pager',{edit:false,add:false,del:false});
setSearchSelect('StatusCode');
jQuery("#grid").jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch: "cn"});
This is the json response I get from the server on initial load.
{
"Total":2,
"Page":1,
"Records":28,
"Rows":[
{
"PKId":1234,
"OrderNumber":"XXXXXX97",
"Cancel":"Cancel",
"OrderDate":"Jul 11 2012 12:37PM",
"Warehouse":"",
"Bucket":"xxxxxxxx",
"StatusCode":"Shipped Complete",
"StatusLink":"View Info",
"TrackingNumber":"xxxxxxx",
"TransportCompany":"xxxxxxxx",
"Destination":"xxxxxxx",
"BucketId":110,
"ShippingEmail":"xxxxxxxx",
"OrderedBy":"xxxxxxxx",
"OrderItem":"xxxxxxx"
},
.... MORE DATA HERE ... 20 OBJECTS ALL-TOGETHER WITHIN Rows Array
{
"PKId":13434,
"OrderNumber":"XXXXXX97",
"Cancel":"Cancel",
"OrderDate":"Jul 11 2012 12:37PM",
"Warehouse":"",
"Bucket":"xxxxxxxx",
"StatusCode":"Shipped Complete",
"StatusLink":"View Info",
"TrackingNumber":"xxxxxxx",
"TransportCompany":"xxxxxxxx",
"Destination":"xxxxxxx",
"BucketId":110,
"ShippingEmail":"xxxxxxxx",
"OrderedBy":"xxxxxxxx",
"OrderItem":"xxxxxxx"
},
],
"UserData":null
}
Any suggestions?
Btw, the pagination and filtering was working just fine when I used loadonce: true and when I loaded all data at once, however, due to too many records I simply have to switch to server-side.
EDIT
I found the problem. First of all, I am sorry for not including the rest of the code.
You see, I also had loadComplete and that was causing the problem for me.
Code in the question will work, so I want to thank everyone for participating.
This is the loadComplete that caused the problem. Once I removed it it started paging properly.
loadComplete: function() {
setParamsOnComplete();
var myGrid = jQuery("#grid");
var ids = myGrid.getDataIDs();
for (var i = 0, idCount = ids.length; i < idCount; i++) {
jQuery("#"+ids[i]+" a",myGrid[0]).click(function(e) {
var hash=e.currentTarget.hash;// string like "#?id=0"
if (hash.substring(0,6) === "#S?id=") {
var id = hash.substring(6,hash.length);
var text = this.textContent || this.innerText;
dialog.dialog({ title: 'Status Information',
buttons:{ Ok: function() {
jQuery( this ).dialog("close");
}
},
open: function() {
jQuery('.ui-dialog-buttonpane').find('button:contains("Ok")').css('font-size', '10px');
}
});
dialog.dialog('open');
}
if (hash.substring(0,6) === "#C?id=") {
var id = hash.substring(6,hash.length);
var text = this.textContent || this.innerText;
var changed = false;
var additionalMesages = "";
jQuery.post("DataFetcher.asp", { 'action': "cancelOrder", 'id':id }, function(xml) {
changed = (xml === 'True');
additionalMesages = xml;
}).success(function(){
if (changed){
showDialogCustomTitle("Success", "You've successfully cancelled the order " + id + ".");
jQuery("#grid").setGridParam({datatype:'xml', page:1}).trigger('reloadGrid');
}else if (additionalMesages.split("_")[1] == "2"){
showDialogCustomTitle("Error", additionalMesages.split("_")[2]);
}else if (additionalMesages.split("_")[1] == "1"){
showDialogCustomTitle("Error", additionalMesages.split("_")[2]);
}
});
}
//e.preventDefault();
});
}
},
Next task for me is to perhaps figure out why loadComplete cause the problem.
EDIT 2
Found the first issue with loadComplete. I was too tired last night to notice it, but the leftover code from the period when this grid was populated with xml and paged on client side definitely caused the problems. Thank you all for involvement again. :)
jQuery("#grid").setGridParam({datatype:'xml', page:1}).trigger('reloadGrid');
Since you have set loadonce:false, the request for paging and filtering try to get processed at the server side. Since that may not probably happening in your case, there will be no data to return to and set in the jqGrid.
If you are using loadonce:false and datatype:"json" jqGrid option then your server must implement the pagination of your grid. The server receives some parameters which is appended to the url in case of the 'GET' requests or sent in the HTTP body in case of "POST" requests namely : rows, page, sidx, sord.
For example if your table have a column with the index 'Col1' as the current sort column and rowNum: 20 then your url will be appended with baseUrl?rows=20&page=1&sidx=Col1&sord=asc. Your server side coding should modify your query for data so that it is to be having ORDER BY (Col1 datafield in the table) asc and rowNum from 1 to 20.
If you have done as stated above and it is not working, you should verify your server code.
Hi I am trying to get showlink formatter working by following this document from trirand.
What I want to achieve is a hyperlink I can click for a edit view to update/edit records. But for some reason, the column are empty where I want show a hyperlink.
Here is my code snippets, and link is the last column:
<script type="text/javascript">
$(document).ready(function () {
$("#grid_products").jqGrid({
jsonReader: {
repeatitems: false,
id: 'Guid'
},
url: '/Product/jqgridJSON/',
datatype: 'json',
mtype: 'GET',
colNames: ['ProductCode', 'ProductDescription', 'DefaultSellPrice', 'LastCost', 'Edit'],
colModel: [
{ name: 'ProductCode', index: 'Productcode' },
{ name: 'ProductDescription', index: 'ProductDescription' },
{ name: 'DefaultSellPrice', formatter: 'currency', index: 'DefaultSellPrice' },
{ name: 'LastCost', formatter: 'currency', index: 'LastCost' },
{ name: 'MyLink',
edittype: 'select',
formatter: 'showlink',
formatoptions: { baseLinkUrl: '/Product/Update/', idName: 'Guid' }
},
],
pager: '#pager',
rowNum: 10,
rowList: [20, 50, 100, 200],
sortname: 'ProductCode',
sortorder: 'asc',
viewrecords: true,
width: 'auto',
height: 'auto',
caption: 'Products'
}).navGrid('#pager', { edit: true, add: false, del: false });
});
</script>
#{
ViewBag.Title = "JSONGrid";
}
<h2>JSONGrid</h2>
<table id="grid_products"></table>
<div id="pager"></div>
The formatter from jqGrid is working for currency, but for some reason, it just didn't shown for hyperlink.
Update:
Got it working by using custom formatter.
...
{ name: 'MyLink',
formatter: myLinkFormatter,
},
...
function myLinkFormatter (cellvalue, options, rowObjcet) {
return 'Edit this product';
}
I suppose that you fill no value in JSON input for the 'MyLink' column. Because of this the hyperlink is empty. If you want to place the link with any fixed text in column I would recommend you to use custom formatter. See the recent answer for an example.
One more possible solution way is to use formatter: 'showlink' and include jsonmap: function() { return "Edit"; } to the 'MyLink' column definition. In the case you will not need to include in the JSON data "MyLink":"Edit" for every row of data. It's important to understand that the trick works only in case of usage jsonReader: {repeatitems: false} (so it should work for your grid).
If you have another problem you should include in the text of your question the JSON data which you use.
Some small remarks to your current code:
the usage of edittype: 'select' together with formatter: 'showlink' has no sense. You should remove it if you will do use formatter: 'showlink'.
the parameter height: 'atuo' should be height: 'auto'.
pager: $('#pager') is better to replace to pager: '#pager'. If you use pager: $('#pager'), the jqGrid will replace it internally to pager: '#pager' and the object $('#pager') will be discarded.
If you use jsonReader: { id: 'Guid'} and you don't plan to show the guids to the user you can remove the 'Guid' column from the grid. The id (the Guid in your case) will be used to assign ids of <tr> elements (table rows) of the grid. So you don't need to hold the same information twice