JQGrid dynamically created column headers - jqgrid

I am creating column headers from the rows of a mysql table (Button1) and it works fine. eg: I get headers |A|B|C| in the grid when I query the table for the rows A, B, C.
Button2 queries the same table to get different rows eg D, E. Both queries return expected data.
But, the new header data from Button2 is appended to the column headers created from Button1. ie I get |A|B|C|D|E|.
What I want is just the headers |D|E|. How can I clear the old column headers and replace with the new?
Thanks for any help.
var ColModel = []
var availabilitydept = ''
$("#button1").click(function() {
availabilitydept = 'de85768424332'
set_up_avgrid()
});
$("#button2").click(function() {
availabilitydept = 'de56827997021'
set_up_avgrid()
});
function set_up_avgrid()
{
$("#avgrid").jqGrid("GridUnload")
$('#avgrid').jqGrid('clearGridData');
create_colmodel()
create_grid()
}
function create_colmodel()
{
ColModel.push({name :'Date',index: 'dateindex',resizable : false, align:'left',
frozen : true, width : 80, search: false,
resizable : false});
$.ajax
({
url: 'tl2_get_rooms_by_dept.php',
type: 'GET',
async: false, // ** it don't work with async true.
data: 'userid=' + 'TL2-0001'
+ '&deptid=' + availabilitydept,
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
ColModel.push({name: row.roomname, index: row.roomname + i, align:'center', resizable : false, width:50, search:false});
}
}
});
}
function create_grid()
{
$("#avgrid").jqGrid(
{
shrinkToFit: false,
height : 200,
width : 290,
colModel: ColModel,
});
}

Solved: I'm sure there are better ways but what I ended up doing was to change my query to select all rows from the mysql table, then create the grid. Of course the grid then had a column for each row in the table. To get rid of the unwanted columns I composed a function to loop through the column names and hide/show as required using.
$"#avgrid").jqGrid('hideCol',[row.roomname]);
$("#avgrid").jqGrid('showCol',[row.roomname]);

Related

How to get row ID by row Data in jqgrid (Not by selected row)

I want to get the row id by content of cell in jqGrid (Not by selected row).
By PRODUCTID, I can get the row id.
e.g. for PRODUCTID is ABCD, I can get 2.
The column PRODUCTID is unique.
Please give me some advices.
Thanks a lot.
My code sample:
$("#project_jqGrid").jqGrid({
url: 'project/projectQuery.php',
mtype: "POST",
datatype: "json",
page: 1,
colModel: [
{ label : "PRODUCTLINE",
//sorttype: 'integer',
name: 'PRODUCTLINE',
//key: true,
width: 100,
editable:true,
editoptions:{readonly:'readonly'}
},
{ label : "GPOWNER",
//sorttype: 'integer',
name: 'GPOWNER',
//key: true,
width: 150,
editable:true,
editoptions:{readonly:'readonly'}
},
{ label : "PRODUCTID",
//sorttype: 'integer',
name: 'PRODUCTID',
key: true,
width: 100,
editable:true,
editoptions:{readonly:'readonly'}
},
],
loadComplete: function() {
$.ajax({
dataType: 'json',
url : "project/projectDifferQuery.php", // your php file
type : "GET", // type of the HTTP request
success : function(data){
// I can get PRODUCTID from mysql database
// I want to get rowid to change cells color by PRODUCTID
// ........
// Change Cells Color(I need to get '5' by position of PRODUCTID)
//$('#project_jqGrid').jqGrid('setCell',5,"GPOWNER","",{'background-color':'#FF4545'});
}
});
},
loadonce: true,
viewrecords: true,
width: 'auto',
height: 'auto',
rowNum: 20,
pager: "#project_jqGridPager"//,
});
> Versions: - jqGrid 5.1.1
If the ProductID is unique and the grid contains ProductID as the column name in colModel, then it's recommended to add key: true to the column definition. It forces jqGrid to use the value from ProductID as the rowid.
It's important to understand that the code of jqGrid require to set unique id attribute to every row (<tr> element) of jqGrid. See here. Thus the input data of jqGrid have to contain rowid information. There are many alternative formats for the input data of jqGrid. In the most common way, the input data should contain id property. If your input data uses ProductID as the unique id of the row, then you can add the option jsonReader: { id: "ProductID" } to inform jqGrid about that. In that case you will not need to include ProductID as the column in colModel.
It is little difficult to understand what you want to get - I think you mean rowIndex, so here are some methods which can help.
Methods
getGridRowById( string rowid)
Return the row with id = rowid as document object
getInd(string rowid, [boolean rowcontent])
Returns the index of the row in the grid table specified by grid id row - rowid. If rowcontent is set to true it returns the row document object
If you have the row as document object you can get the index and id. Suppose the rowdata is the document row, then
rowdata.rowIndex is the index
rowdata.id is the id

Kendo Grid with Server Filtering Sends Object Instead of Value

I have a Kendo Grid where I am filtering one of the columns with a MultiSelect control. When I click the "Filter" button it sends [object Object] to the server as the filter value. How can I fix it so it sends the values of the selected item(s). Note, I am server filtering the grid not the multi select control.
Initialization of the multiselect
var regionddl = element.kendoMultiSelect({
dataTextField: "Value",
dataValueField: "Value",
optionLabel: "Select One...",
dataSource: {
transport: {
read: {
data: "",
dataFilter: function (data) {
var msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
contentType: "application/json; charset=utf-8",
type: "POST",
url: "SearchSites.aspx/GetRegions"
}
}
}
}).data("kendoMultiSelect");
Here is the JSON that Kendo is sending to the server. Notice there are two object Object items because I selected two items in the filter.
[{\\\"field\\\":\\\"Region\\\",\\\"operator\\\":\\\"eq\\\",\\\"value\\\":\\\"[object Object],[object Object]\\\"}]
If you want to see an example of what multiselect filtering looks like in a grid, you can see this jsbin
http://jsbin.com/upEPEqU/3/edit
To change this you need to set the valuePrimitive option to true.

jqgrid - copy row(s) with data from database

I'm trying to copy a row, but I'm using the data from a database, and I'm returning it with JSON. I'd like to know if it's possible to make a copy of a row, and if can I delimited the number of times that I can copy the rows. For example, I need to copy a row with id = 6, but I need to make 5 copies of this row. How can I do that?
You could make main work on server side not on client
In jqgrid decraration something like this:
grid.jqGrid({
...
loadComplete: function(data) {
var ids = grid.jqGrid('getDataIDs');
for (var i=0;i<ids.length;i++) {
var id=ids[i];
var rowData = thisGrid.jqGrid('getRowData', id);
grid.jqGrid('setCell', id, 'buttons', '<input type="button" class="copy" value="Copy">');
}
$('button.copy').click(function (e) {
var id = $(e.target).parents('tr')[0].id;
$.ajax({
url: 'some_url',
dataType : "json",
data: {'id': id},
timeout: 10000,
type: 'POST',
success: function (data) {
grid.trigger('reloadGrid');
},
});
});
}
....
});
In php part something like this
$array = array(
'success'=>false
);
if(isset($_POST['id])) {
if($db -> num_rows($q = $db->query("SELECT FROM ... WHERE `id` = ".intval($_POST['id'])) == 1) {
$row = $db -> fetch_assoc($q);
$db->query("INSERT INTO .....);
$array['success'] = true;
}
}
echo json_encode($array);
If you want to copy more than one time you could add some dialog on client side to input number of copies
use getRowData To Grab a Single row from jqgrid and then create an array by var s = new Array() and push the single row no of times you want ..
create a new column inside jqgrid .. using formatter Formatter In jQgrid place a link inside that column write handler for click over that link .. on that handler use getrowdata and grab the fields and then make a ajax call to send to the server...

JSON.stringify(data)

I have the following .ajax
$.ajax({
url: urlpath,
type: 'POST',
dataType: 'json',
data: JSON.stringify(json),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(JSON.stringify(data));
},
error: error
});
What I am passing back is a list with 3 columns. When I do alert(JSON.stringify(data));
it shows me the data - 3 columns and 4 rows of data. How do I go about parsing this and storing it into a table?
Say you have a table with an id="my-table", you can substitute your alert with something like:
$('#my-table tr').each(function (r) {
$('td', this).each(function (c) {
// here you cycle on every td (column) of a row to populate it
// example with 3 columns assuming this json structure
// {
"row1": [ 100, 200, 300],
"row2": [ 50, 200, 400 ],
"row3": [ 10, 300, 200]
// }
this.innerHTML = data["row"+r][c]
})
});
$('#my-table tr')... find create an array with your table rows
$('td', this)... apply an anonimous function on every td of the loop current tr (this acts as the search context for tds

Jqgrid: navigation based on the selected row

I was trying to enable navigation based on a selected row. So, the user select a row from jQgrid, and when press the show (is there a show button for the grid, I saw edit, add etc), it needs to go to a new page based on the url (part of the row).
$(document).ready(function () {
function getLink() {
// var rowid = $("#customer_list").jqGrid('getGridParam', 'selrow');
var rowid = $("#customer_list").getGridParam('selrow');
var MyCellData = $("#customer_list").jqGrid('getCell', rowid, 'dataUrl');
return MyCellData;
}
$("#customer_list").jqGrid({
url:'mytestList',
editurl:'jq_edit_test',
datatype: "json",
colNames:['Call Id','Title','dataUrl'],
colModel:[
{name:'callId', width:80, search:false},
{name:'title', width:200, sortable:false},
{name:'dataUrl',hidden:true}
],
rowNum:10,
sortname:'lastUpdated',
sortorder: 'desc',
pager:'#customer_list_pager',
viewrecords: true,
gridview: true
}).navGrid('#customer_list_pager',
{add:true,edit:true,del:false,search:true,refresh:true},
{closeAfterEdit:true, afterSubmit:afterSubmitEvent}, // edit options
{addCaption:'Create New something', afterSubmit:afterSubmitEvent,
savekey:[true,13]}, // add options
{afterSubmit:afterSubmitEvent} // delete options
);
$("#customer_list").jqGrid('filterToolbar');
});
so, the url is passed for each row as dataUrl. I'm trying to read it and set to the button. When debug through firebug, the rowid was 223 (there were only 12 rows in the grid), and the cell value is empty. Currently the button is kept outside the grid, but it may better to be it part of the vavGrid
thanks.
The code like following could solve your problem
$("#customer_list").jqGrid ('navButtonAdd', '#customer_list_pager',
{ caption: ""/*"Show"*/, buttonicon: "ui-icon-extlink", title: "Show Link",
onClickButton: function() {
var grid = $("#customer_list");
var rowid = grid.jqGrid('getGridParam', 'selrow');
window.location = grid.jqGrid('getCell', rowid, 'dataUrl');
}
});
You could just make the show button be part of each row in the grid and use a custom formatter to turn it into a URL.
Based on the example in the wiki, you'll probably need something along the lines of
function myformatter ( cellvalue, options, rowObject )
{
return "Show";
}

Resources