I have a requirement to provide a button on a grouped row , when onclick of that button , I should capture rowData. I've tried to implement this with custom formatter , grid.SetCell option, but didn't work.
Here is Sample code:
grid.jqGrid({
datatype: 'local',
colNames: ['Id', 'Order Id', 'Name', 'OrderName'],
colModel : [
{ name: 'ID', index: 'ID', editable: true}, //// I grouped by this column
{ name: 'OrderID', index: 'OrderID', width: 30, align: 'center'},
{ name: 'Name', index: 'Name', width: 30, align: 'center'},
{ name: 'OrderName', index: 'OrderName', width: 30, align: 'center'}
],
groupingView: {
groupField: ['ID'],
groupCollapse: true,
groupColumnShow: [false],
groupText: ['<b>{0}</b></div><input type = "button" class = "button" value = "NEW" id = "btnNew" style = "width:100px; hieght:10px" onclick = "javascript:AddNew({OrderID})" /><<b>{1} Orders</b>']
function AddNew(orderId)
{
//// DO SOME THING
}
In above example my grid will be grouped by Id , on each grouped row I need to create a button which onclick event should consist of Order Id. (Order Id is same for all the rows under each group). I need to show Count here also.
I was not able to pass order Id in group Text above, then I use custom formatter on ID column like this .
var html ;
formatter: function(cellValue, options, rowObject)
{
if ((options.rowId.toString()).indexOf("listghead") === -1) {
html = cellvalue + "<input type = "button", value = "New" onclick = AddNew(' +rowObject[1] +')
}
return html;
}
rowObject value has been passed but grouping was broken. If I don't use the above if condition grouping works fine, but onclick event is breaking.
Help me .
Thanks in Advance.
You can get the row value through rowObject so:
html = rowObject.childNodes[1].childNodes[0].wholeText;
This code return a string with the content of rowObject to that columm
You can just pass the rowObject when it comes to group header , and it is not undefined or null when it comes to groupheader.
Just test it using alert(rowObject) when you detect it's group header.
Related
//Hidden Input element
//my grid details:
$("#jqGrid").jqGrid({
url: '#Url.Action("EditedEventData", "Calendar" ,new{ })' + '?CountryId=' + #countryid + '&CityId=' + #cityid ,
async: true,
datatype: "json",
colModel: [
//label: "Edit Actions",
name: "",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
edit: true,
add: true,
del: true,
editOptions: {},
addOptions: {},
delOptions: {
url:'#Url.Action("RemoveEvent", "Calendar")'+ '?HolidayId='+document.getElementById('hdnEventId').value ,
//mtype: 'POST',
}// **here it is showing hdnEventId value empty**
}
}
],
onSelectRow : function(id){
console.log('inside onSelectRow');
alert(id);
document.getElementById('hdnEventId').value=id;
alert(document.getElementById('hdnEventId').value);
},
sortname: 'EventDate',
loadonce: true,
width: 750,
height: 200,
rowNum: 150,
pager: "#jqGridPager"
});
I am unable to access id of onSelectRow in delOptions action method.
So thought of taking a hidden html element and store the value but it is showing empty.
Thanks in advance
When a delete is performed the id is automatically send to the server. The parameter which is obtained via post is named id.
If you additionally want to fill a id on deleting a rows you can use some events to fill the field you want. These are described here. In the same documentation see the chapter What is posted to the server .
To fill the id in another field when a row is deleted I think the good choice is to use either serializeDelData or afterSubmit events - see the events on the same link.
When use these events the parameter postdata contain the id. By example in serializeDelData (set this in delOptions) this can look like
serializeDelData : function( postdata ) {
var id = postdata.id;
document.getElementById('hdnEventId').value=id;
return postdata;
}
Remember both events should return some params
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
I have jqGrid table with many columns. Searching in grid is made using filter toolbar. For most of them search is just simple default operator. For one datetime column I want different kind of operators and datepicker selector.
I have added dataInit datepicker initialization to searchoptions, necessary operators to searchoptions.sopt. To show this operators I have set searchOperators to true. So for this column all is ok. I have datepicker with operator selector popup. But for all other columns default operator icon is shown on the left of it. It is annoying as operator is default and user couldn't change it. So is there is some possibility to hide them using jqGrid API? As far as I could see I could hide this only using my custom code:
I need to check my column model and after rendering of grid (may be in loadComplete) for all columns that have empty sopt or sopt.length == 0 to remove operator selector. Or add CSS class that hide it. Not sure which of these solution is better (hide or remove) because removing could broke some logic, and hiding could affect width calculation. Here is sample of what I mean on fiddle
function fixSearchOperators()
{
var columns = jQuery("#grid").jqGrid ('getGridParam', 'colModel');
var gridContainer = $("#grid").parents(".ui-jqgrid");
var filterToolbar = $("tr.ui-search-toolbar", gridContainer);
filterToolbar.find("th").each(function()
{
var index = $(this).index();
if(!(columns[index].searchoptions &&
columns[index].searchoptions.sopt &&
columns[index].searchoptions.sopt.length>1))
{
$(this).find(".ui-search-oper").hide();
}
});
}
Does anybody have some better ideas?
I find the idea to define visibility of searching operations in every column very good idea. +1 from me.
I would only suggest you to change a little the criteria for choosing which columns of searching toolbar will get the searching operations. It seems to me more native to include some new property inside of searchoptions. So that you can write something like
searchoptions: {
searchOperators: true,
sopt: ["gt", "eq"],
dataInit: function(elem) {
$(elem).datepicker();
}
}
I think that some columns, like the columns with stype: "select", could still need to have sopt (at least sopt: ["eq"]), but one don't want to see search operators for such columns. Specifying of visibility of searching operations on the column level would be very practical in such cases.
The modified fiddle demo you can find here. I included in the demo CSS from the fix (see the answer and the corresponding bug report). The full code is below
var dataArr = [
{id:1, name: 'steven', surname: "sanderson", startdate:'06/30/2013'},
{id:2, name: "valery", surname: "vitko", startdate: '07/27/2013'},
{id:3, name: "John", surname: "Smith", startdate: '12/30/2012'}];
function fixSearchOperators() {
var $grid = $("#grid"),
columns = $grid.jqGrid ('getGridParam', 'colModel'),
filterToolbar = $($grid[0].grid.hDiv).find("tr.ui-search-toolbar");
filterToolbar.find("th").each(function(index) {
var $searchOper = $(this).find(".ui-search-oper");
if (!(columns[index].searchoptions && columns[index].searchoptions.searchOperators)) {
$searchOper.hide();
}
});
}
$("#grid").jqGrid({
data: dataArr,
datatype: "local",
gridview: true,
height: 'auto',
hoverrows: false,
colModel: [
{ name: 'id', width: 60, sorttype: "int"},
{ name: 'name', width: 70},
{ name: 'surname', width: 100},
{ name: 'startdate', sorttype: "date", width: 90,
searchoptions: {
searchOperators: true,
sopt: ['gt', 'eq'],
dataInit: function(elem) {
$(elem).datepicker();
}
},
formatoptions: {
srcformat:'m/d/Y',
newformat:'m/d/Y'
}
}
]
});
$("#grid").jqGrid('filterToolbar', {
searchOnEnter: false,
ignoreCase: true,
searchOperators: true
});
fixSearchOperators();
It displays the same result like youth:
Each row has an id in our db different to the jqgrid row id. How can I send this lineid when saving a row?
Also, is there a way to delete a row?
This is my code so far:
var mydata = [
{
lineItemId: "785",
productSku:"n123",
productName:"hello there",
pieces:"123",
value:"23.00",
line:"123"
}
,
{
lineItemId: "803",
productSku:"n1234",
productName:"hello there",
pieces:"123",
value:"23.00",
line:"123"
}
];
var colNames = ['SKU','Product Name', 'Pieces','Total Value','Line Number'];
var colModel = [
{name:'productSku', index:'productSku', width:10, sorttype: 'text', editable:true},
{name:'productName', index:'productName', width:60, editable:true},
{name:'pieces', index:'pieces', width:10, sorttype: 'int', editable:true, formatter: 'integer'},
{name:'value', index:'value', width:10, sorttype: 'int', editable:true, formatter: 'number'},
{name:'line', index:'line', width:10, sorttype: 'int', editable:true, formatter: 'integer', formatoptions:{thousandsSeparator: ""}}
];
initOrdersJqGrid("orderContent", mydata, '<xsl:value-of select="$datapath/OrderId"/>', colNames, colModel, "sku", "desc");
var orderLineOptions = {
keys: true,
aftersavefunc: function (rowid, response, options) {
// only update page if orderis is nil i.e. a new order
if($('#orderidlabel').text() == "") {
log('saving order line item from order with no id yet.');
var dummy = $('<div />').html(response.responseText);
var id = dummy.find('#orderId').val();
$('#orderidlabel').text(id);
$('#orderId').val(id);
$('button[value="Save Order"]').trigger('click');
}
}
}
function initOrdersJqGrid(id, data, orderid, colNames, colModel, defaultSortColumn, defaultSortOrder) {
$("#" + id + "Table")
.jqGrid({
datatype: "local",
data: data,
colNames: colNames,
colModel: colModel,
localReader: { id: "lineItemId"},
pager: '#' + id + 'Pager',
autowidth: true,
gridview: true,
autoencode: true,
height: "auto",
forceFit: true,
shrinkToFit: true, //Width of columns should be expressed in integers which add to 100
sortname: defaultSortColumn,
sortorder: defaultSortOrder,
url: "fs/servlet/CS",
editurl: "CS?action=com.agistix.webinterface.controllers.OrderIC,saveLineItems&orderId=" + orderid
})
.jqGrid('navGrid',"#" + id + "Pager",{edit:false,add:false,del:false,search: false, refresh: false})
.jqGrid('inlineNav',"#" + id + "Pager", { addParams: { addRowParams: orderLineOptions }, editParams: orderLineOptions});
}
If you use datatype: "local" then the items from the array of input data specified by data parameters should have additional property id which specify the value of id attribute of every row (<tr>) of the grid. If you prefer to have another name of the rowsid property you can use localReader to specify it. For example localReader: { id: "Id" } option inform jqGrid to get value of id attribute of rows (rowids) from the Id property. In the case the items of your data should bi like below
{
Id: 76453
productSku:"n123",
productName:"hello there",
pieces:"123",
value:"23.00",
line:"123"
}
The value of id property need be unique.
If you have already some column in the grid which contains id from some database table you don't need to add the same value with id property. Instead of that you can just key: true in the column. jqGrid allows to place key: true in only one item of colModel.
One more common problem with ids of rows it's important to understand. If you need to place more as one grid on a page or if you need to use Subgrid as Grid then you can still have one problem. The ids in database are unique in a table, but one can have the same ids in multiple tables. On the other side the ids of HTML elements (inclusive <tr> elements used for rows) must be unique over the whole page.
To solve the problem one can use idPrefix option of jqGrid. For example you have INT IDENTITY column in the database for the primary key of the table in the database. In the case you will have integers as native ids for rowids. The values can be for example 3, 5, 40 in the first grid. By usage idPrefix: "g1_" the ids assigned to the rows (to <tr> elements) will be "g1_3", "g1_5", "g1_40". So usage of idPrefix: "g1_" for the first grid and another value like idPrefix: "g2_" can solve the problem with potential id duplicates. It's important that jqGrid automatically strip the prefix idPrefix from rowid if it sends some data to the server (if you use editing in the grid for example). One can distinguish "id" and "rowid" names. The "rowids" will be always with prefix. You can use $.jgrid.stripPref function to cut the prefix.
I would like to know how to display multiple values in a single column in jqGrid
Here is a sample of my current grid definition.
$("#grid1").jqGrid({
url: 'Default.aspx/getGridData',
datatype: 'json',
...
colModel: [
...
//contains the input type ('select', etc.)
{ name: 'InputType', hidden:true },
...
//may contain a string of select options ('<option>Option1</option>'...)
{
name: 'Input',
editable:true,
edittype:'custom',
editoptions:{
custom_element: /* want cell value from InputType column here */ ,
custom_value: /* want cell value from Input column here */
}
},
...
]
});
You can do this easily by using a Custom Formatter on your column model.
A custom Formatter is a javascript function with the following parameters:
cellvalue - The value to be formatted
options - { rowId: rid, colModel: cm} where rowId - is the id of the
row colModel is the object of the properties for this column getted
from colModel array of jqGrid
rowObject - is a row data represented in the format determined from
datatype option
So a function can be declared like so:
function myformatter ( cellvalue, options, rowObject )
{
// format the cellvalue to new format
return new_formated_cellvalue;
}
And is defined on your column like this:
{name:'price', index:'price', width:60, align:"center", editable: true,
formatter:myformatter },
So in your case you can use the rowObject parameter in the custom formatter to populate your additional values.
For Example.
Column Model
{name:'employee_id', index:'employee_id', width:60, align:"center", editable: true,
formatter:myformatter, label:'Employee' }
Formatter
function myformatter ( cellvalue, options, rowObject )
{
return cellvalue + ' ' + rowObject.email + ' ' + rowObject.user_name;
}
And if this is defined on your employee_id column it would display in the cell:
employee_id email username
Here is a jsFiddle example showing it working.