export jqgrid data into excel on checkbox selection - javascript

I have bind the jqGrid from MVC controller , below is my jqgrid code . I want to export selected checkbox row data to csv , i have gone through all code's but every one providing sample local data, but i am binding from server to jqGrid,so when i select the checkbox rows in jqGrid and click on "Export " button the entire row should export to csv, can anybody have the solution ?
$('#jQGrid').jqGrid({
search: true,
multiboxonly: true,
colNames: ["PayloadCorrelationId", "Export", "Asset", "DateReported", "ErrorType", "Error", "Latitude", "Longitude", "Payloadurl"],
colModel: [
{ name: 'CorrelationId', jsonmap: 'CorrelationId', hidden: true, width: 2 },
{ name: "", editable: true, edittype: "checkbox", width: 45, sortable: false, align: "center", formatter: "checkbox", editoptions: { value: "1:0" }, formatoptions: { disabled: false } },
{ name: 'Device', jsonmap: 'Device', width: 60 }, { name: 'DateReported', jsonmap: 'DateReported', width: 100 },
{ name: 'ErrorType', jsonmap: 'ErrorType', width: 85 },
{ name: 'Error', jsonmap: 'Error', width: 140 },
{ name: 'Latitude', jsonmap: 'Latitude', width: 80 }, { name: 'Longitude', jsonmap: 'Longitude', width: 80 },
{ name: 'Payloadurl', jsonmap: 'Payloadurl', width: 180, formatter: 'link' }],
cellEdit: true,
pager: jQuery('#divpager'),
rowList: [5, 20, 50, 100],
rowNum:5,
sortorder: "desc",
datatype: 'json',
width: 900,
height: 'auto',
viewrecords: true,
mtype: 'GET',
gridview: true,
loadonce: true,
url: '/DataIn/DataInSearchResult/',
emptyrecords: "No records to display",
onSelectRow: true,
onSelectRow: function (id, status) {
var rowData = jQuery(this).getRowData(id);
configid = rowData['CorrelationId'];
alert(configid);
// Add this
var ch = jQuery(this).find('#' + id + ' input[type=checkbox]').prop('checked');
if (ch) {
jQuery(this).find('#' + id + ' input[type=checkbox]').prop('checked', false);
} else {
jQuery(this).find('#' + id + ' input[type=checkbox]').prop('checked', true);
}
// end Add
rowChecked = 1;
currentrow = id;
},
loadComplete: function () {
var ts = this;
if (ts.p.reccount === 0) {
$(this).hide();
} else {
$(this).show();
$("#lblTotal").html($(this).getGridParam("records") + " Results");
}
}
});

Just to clarify, There must be any buttons on clicking which the csv will generate from the selected check box. If it is so then loop through the grid data to filter out checked rows. You can loop through the grid data easily on firing the button event. Based on the resultant data create the csv.

Related

How to get all row ids of jqgrid by class

I want to get all row ids by use of row css class of a jqgrid in a method called in gridcomplete.But it is only returning rows of current page.
I want to get all row ids present in the jqgrid.
Below is my code.
function GetAllCompanyProducts(productData) {
/// <summary>method to load the Proposal grid</summary>
//Load the grid
var tabelWidth = $("#tblCompanyProducts").width();
jQuery("#tblCompanyProducts").jqGrid({
datatype: 'local',
data: productData,
jsonReader: { repeatitems: false },
loadui: "block",
autowidth: true,
mtype: 'get',
rowNum: 30,
rowList: [30, 100, 200],
viewrecords: true,
colNames: ['ProductId', 'ProductName', 'Price'],
colModel: [
{ name: 'ProductId', index: 'ProductId', width: '30%' },
{ name: 'ProductName', index: 'ProductName', width: '30%' },
{ name: 'Price', index: 'Price', width: '30%' }
],
sortname: 'ProductId',
sortorder: 'asc',
caption: "Product List",
width: tabelWidth - 10,
pager: '#divPager',
height: "100%",
hoverrows: true,
onPaging: function () {
$("#tblCompanyProducts").trigger('reloadGrid');
},
});
$("#tblCompanyProducts").jqGrid('setGridParam', { gridComplete: MakeGridRowsDraggable($("#" + this.id)) });
}
function MakeGridRowsDraggable(grid) {
/// <summary></summary>
/// <param name="grid" type=""></param>
//$("#tblCompanyProducts").val(new Date().getTime());
var searchResultsRows = $("#tblCompanyProducts .ui-row-ltr");
}
The above code returning only the rows set in the first page.
Can anybody help me on this..

jqGrid shows + sign even after subgrid has no data using xml

I am using jqGrid to show data with subgrid.
Data is in xml format.
$("#UDFs").jqGrid({
ajaxGridOptions: { contentType: 'application/xml; charset=utf-8' },
datatype: 'xmlstring',
datastr: data,
xmlReader: { root: "Response", row: "Data>UDFS>row", repeatitems: false, id: "FieldID" },
subGrid: true,
subgridtype: 'xml',
subGridOptions: { "plusicon": "ui-icon-triangle-1-e", "minusicon": "ui-icon-triangle-1-s", "openicon": "ui-icon-arrowreturn-1-e" },
subGridRowExpanded: function (subgrid_id, row_id) {
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id + "_t";
pager_id = "p_" + subgrid_table_id; $("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table><div id='" + pager_id + "' class='scroll'></div>");
jQuery("#" + subgrid_table_id).jqGrid(
{
datastr: $($.parseXML(data)).find('Response>Data>UDFS>row:has(FieldID:contains('+ row_id+'))').XmlToString(),
datatype: "xmlstring",
colNames: [ 'Code', 'Name'],
colModel: [
{ name: "Code", index: "Code", width: 130 },
{ name: "Name", index: "Name", width: 70 }
],
xmlReader: { root: "row", row: "ValidValues>row", repeatitems: false, id: "FieldID" },
rowNum: 20,
pager: pager_id,
height: '100%'
});
jQuery("#" + subgrid_table_id).jqGrid('navGrid', "#" + pager_id, { edit: false, add: false, del: false })
},
colNames: ['#', 'TableID', 'SAPType', 'SAPSubType', 'SAPValidation', 'FieldID', 'AliasID', 'Descr', 'TypeID', 'SizeID', 'EditSize', 'Dflt', 'NotNull', 'RTable', 'RelUDO', 'ValidValues'],
colModel: [
{
index: 'Tick',
name: 'Tick',
width: 50,
resizable: false,
editable: true,
align: 'center',
edittype: 'checkbox',
formatter: "checkbox",
formatoptions: { disabled: false },
classes: 'check',
editrules: { required: false }, editoptions: { size: 39, value: "True:False" }
},
{ name: 'TableID', index: 'TableID', align: "left", width: 40, hidden: true },
{ name: 'SAPType', index: 'SAPType', align: "left", width: 80 },
{ name: 'SAPSubType', index: 'SAPSubType', align: "left", width: 80 },
{ name: 'SAPValidation', index: 'SAPValidation', align: "left", width: 80 },
{ name: 'FieldID', index: 'FieldID', align: "left", width: 40, hidden: false },
{ name: 'AliasID', index: 'AliasID', align: "left", width: 180 },
{ name: 'Descr', index: 'Descr', align: "left", width: 180 },
{ name: 'TypeID', index: 'TypeID', align: "left", width: 80 },
{ name: 'SizeID', index: 'SizeID', align: "left", width: 80 },
{ name: 'EditSize', index: 'EditSize', align: "left", width: 80 },
{ name: 'Dflt', index: 'Dflt', align: "left", width: 80 },
{ name: 'NotNull', index: 'NotNull', align: "left", width: 80 },
{ name: 'RTable', index: 'RTable', align: "left", width: 80 },
{ name: 'RelUDO', index: 'RelUDO', align: "left", width: 80, hidden: false },
{ name: 'ValidValues', index: 'ValidValues', align: "left", width: 80, formatter: formatToLink, unformat: UnformatFromLink }
],
rowNum: 15,
mtype: 'POST',
pager: "#UDFsMap",
gridview: true,
rownumbers: true,
loadonce: true,
forceFit: true,
width: 1100,
height: 250,
caption: 'Select UDF from the below list.',
multiselect: false,
loadComplete: function () {
$(this).HideBusy();
},
ondblClickRow: function (rowid, iRow, iCol, e) {
selectedRowId = $("#ObjType").jqGrid('getGridParam', 'selrow');
ObjectTypeID = $("#ObjType").jqGrid('getCell', selectedRowId, 'ObjectTypeID');
// $("#SelectCustomer").dialog('close');
// xmlDoc1 = $.parseXML(xmlString);
// $xml1 = $(xmlDoc1);
// $(this).SetValuesToControl("Landscape", $xml1);
// $("#uxTask").attr("binding", "true");
}
}).jqGrid('navGrid', '#UDFsMap', { edit: false, add: false, del: false, search: true });
When grid displays on page, it shows Plus (+) sign / arrow even if the subgrid does not have data.
Is it possible to hide / remove this Plus (+) sign / arrow when there is no data in subgrid?
UPDATED:
I tried your proposed solution and saw samples also, it works for me from 2nd page onwards. its not working for 1st page.
loadComplete: function (data) {
var grid = $("#UDFs");
var $self = $(this), rowIds = $self.jqGrid("getDataIDs"), item, i, l = rowIds.length;
for (i = 0; i < l; i++) {
item = $self.jqGrid("getLocalRow", rowIds[i]);
debugger;
if (item.ValidValues == null || item.ValidValues.length === 0) {
// subggrid is empty
$("#" + rowIds[i]).find(">.ui-sgcollapsed").unbind("click").html("");
}
}
$(this).HideBusy();
},
When the grid load, it works from 2nd page onward. Please see the screen shot. In the last column (ValidValues), if exist then show subgrid / plus sign otherwise hide.
In below screen shot it is working.
I recommend you to hide the "+" icon of rows which have no subgrids inside of loadComplete callback. The first parameter of callback loadComplete contains all parsed XML data (datastr: data) which you use to fill the grid. See the old answer which describes the main idea of the hiding of the rows. You can get the ids of the rows of the current page by usage of getDataIDs and to find the corresponding item in XML data by the id. Then you can examine the information about subgrids and to hide the icon.
The demo demonstrates the approach in case of usage JSON data. You can do the same with XML data too. You need just change the criteria for testing the input data for the existence of subgrid.
UPDATED: The code which you posed in UDPATED works only with the second part because you use datatype: 'xmlstring'. At the first loading the data in loadComplete are XML data and you should be more careful how to parse it. My demo used JSON instead of XML data. So you should use the demo which I posted as the template, but you have to modify it based on the format of the data which you use.

hyperlink / button with custom function call in jqgrid

I want to add a hyperlink / button in each row of jqgrid, that fires a custom javascript function. Tired of various trials.
jQuery('#ProductListGrid').jqGrid({
url: '/Product/ProductListGrid',
datatype: 'json',
multiselect: true,
height: 250,
autowidth: true,
mtype: 'GET',
loadComplete: addlinks,
colNames: ['ProductId', 'ProductName', 'edit'],
colModel: [
{ name: 'ProductId', index: 'ProductId',key:true, width: 70, hidden: true, editable: true, size: 5 },
{ name: 'ProductName', index: 'ProductName', width: 70, editable: true },
{ name: 'edit', index: 'edit', width: 70},
],
pager: jQuery('#ProductListGrid_pager'),
});
function addlinks() {
var ids = jQuery("#ProductListGrid").getDataIDs();
alert(ids);
for (var i = 0; i < ids.length; i++) {
be = "<a href='#' style='height:25px;width:120px;' type='button' title='Slet' onclick=\"ff()\" >Slet</>";
jQuery("#ProductListGrid").jqGrid('setCell', ids[i],'edit','', { act: be });
}
//for (var i = 0; i < ids.length; i++) {
// jQuery("#ProductListGrid").setCell(i, 'edit', '<a href="#">edit</edit>');
//}
}
function ff()
{
alert("hi");
}
The code in addlinks in is getting executed but there nothing appears in the column. I tried using custom formatting also but I couldnot show custom text "Edit" and link click doesnot fire the js method.
You need to call a formatter for edit column like below :
Add formatter: addLink to the last column :
colModel: [
{ name: 'ProductId', index: 'ProductId',key:true, width: 70, hidden: true, editable: true, size: 5 },
{ name: 'ProductName', index: 'ProductName', width: 70, editable: true },
{ name: 'edit', index: 'edit', width: 70,formatter: addLink},
]
add javascript function :
function addLink(cellvalue, options, rowObject)
{
//to get row Id
alert(options.rowId);
// to get product Id
alert(rowObject.ProductId);
return "<a href='#' style='height:25px;width:120px;' type='button' title='Slet' onclick=\"ff()\" >Slet</a>";
}
More Information on formatter here.

Call Jquery grid inside a function

I have a jquery grid.
I want to change the data of jquery grid on dropdown change event.
So I need to call the jqgrid inside the change event.
below is my code
$("#ddlCategory").change(function () {
UserJqGrid();
GetMapDataOnChange();
});
The first function return a jqgrid and the 2nd function will return a map.
But only 1st time the jqgrid load.After that on change the dropdown list the data of the grid not updated.
my UserJqGrid() function is
$("#list").jqGrid({
url: "<?php echo base_url() ; ?>userController/GetUserGirdData?catIds=" + str + "&cityId=" + cityId,
datatype: 'json',
mtype: 'GET',
colNames: ['Object Id', 'Name', 'Longitute', 'Latitute', 'Country', 'City'],
colModel: [{
name: "id",
index: "id",
key: true,
width: 20,
editable: true,
key: true,
editoptions: {
readonly: true,
size: 10
}
}, {
name: "objName",
index: "objName",
width: 100,
editable: true
}, {
name: "longi",
index: "longi",
width: 30,
align: "left",
editable: true
}, {
name: "lati",
index: "lati",
width: 30,
align: "left",
editable: true
}, {
name: "countryName",
index: "countryName",
width: 50,
align: "left",
editable: true
}, {
name: "cityName",
index: "cityName",
width: 50,
align: "left",
sortable: false,
editable: true
}, ],
pager: '#pager',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id',
sortorder: 'desc',
viewrecords: true,
width: 900,
gridview: true,
shrinkToFit: true,
//rownumbers: true,
height: 200,
caption: 'Shipping Method',
editurl: '../php/EditShipping.php'
});
jQuery("#list").jqGrid('navGrid', '#pager', {
edit: true,
add: true,
del: false,
excel: false,
search: false
});
I solved my problem.
I call this reload event of grid.As the grid is already created so we don't need to call the whole function again.Just need to reload the grid with new data.
jQuery("#list")
.jqGrid('setGridParam',
{
url:"<?php echo base_url() ; ?>userController/GetUserGirdData?catIds=" + str + "&cityId=" +cityId,
datatype: 'json',
mtype: 'GET'
}).trigger("reloadGrid");

jqGrid not displaying pagination links

I have some legacy code here and I am using jqGrid in order to paginate some XML data. The XML contains 354 record and the first 20 of them are displayed as soon as the page loads, but then jqGrid does not display the links to browse the other records and paginate them.
I am sure jqGrid is getting the full XML and it even says Viewing 1 - 20 of 354, but doesn't really let me paginate.
And if I enter the number of the pagination ("2" for page 2, for example) and enter it, it makes an HTTP request (which returns 200 status) and does nothing!
This is the JS code for the pagination:
$(document).ready(function() {
erc_id = $('#erc_id').val();
jQuery("#list4").jqGrid({
url: "/ercs/" + erc_id + "/exemplares.xml",
datatype: "xml",
width: 650,
pager: "gridPager",
height: 'auto',
xmlReader: {
root: "exemplares",
row: "exemplar",
repeatitems: false,
id: "id"
},
colNames: ['Código', 'Referência', 'Num. Controle', 'Dt. Moldagem', 'Traço'],
colModel: [
{
name: 'codigo',
index: 'codigo',
width: 60,
sortable: false},
{
name: 'referencia',
index: 'referencia',
width: 160,
sortable: false},
{
name: 'numero-controle',
index: 'numero-controle',
width: 60,
sortable: false,
align: 'center'},
{
name: 'data-moldagem',
index: 'data-moldagem',
width: 60,
sortable: false},
{
name: 'traco',
index: 'traco',
width: 60,
sortable: false,
xmlmap: "traco>reference"},
],
viewrecords: true,
caption: "Exemplares",
subGrid: true,
subGridRowExpanded: function(subgrid_id, row_id) {
var subgrid_table_id = subgrid_id + "_t";
my_row_id = row_id
$("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table>");
row_id = row_id.replace("5687", "");
jQuery("#" + subgrid_table_id).jqGrid({
url: "/ercs/" + erc_id + "/exemplares/" + row_id + "/cps.xml",
datatype: "xml",
height: 'auto',
width: 550,
xmlReader: {
root: "cps",
row: "cp",
repeatitems: false,
id: "id"
},
colNames: ['Número', 'Carga', 'Idade', 'Prensa', 'Retifica', 'Ruptura', 'retifica', 'N cont antigo'],
colModel: [
{
name: "numero",
index: "numero",
width: 60,
sortable: false},
{
name: "carga",
index: "carga",
width: 50,
sortable: false,
align: 'center'},
{
name: "idade",
index: "idade",
width: 30,
sortable: false,
align: 'center'},
{
name: "prensa",
index: "carga",
width: 30,
sortable: false,
align: 'center'},
{
name: "carga",
index: "carga",
width: 50,
sortable: false,
align: 'center'},
{
name: "ruptura",
index: "ruptura",
width: 50,
sortable: false,
align: 'center'},
{
name: "retifica",
index: "retifica",
width: 50,
sortable: false,
align: 'center'},
{
name: "numero-controle-antigo",
index: "numero-controle-antigo",
width: 50,
sortable: false,
align: 'center'}
]
});
},
ondblClickRow: function(id) {
id = id.replace("5687", "");
if (typeof my_row_id !== "undefined") {
my_row_id = my_row_id.replace("5687", "");
window.location = "/ercs/" + erc_id + "/exemplares/" + my_row_id + "/cps/" + id + "/edit"
} else {
window.location = "/ercs/" + erc_id + "/exemplares/" + id + "/edit"
}
},
});
});​
If you know what is possibly causing this error please tell me.
I would recommend adding a gridComplete function to your grid definition and then you'll be able to easily inspect some of the values that control paging:
gridComplete: function(){
var r = $(this).getGridParam('records');
var p = $(this).getGridParam('page');
var rec = $(this).getGridParam('reccount');
var row = $(this).getGridParam('rowNum');
}
Here is where they are all documented:
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:pager#properties

Categories