YUI 3.13 Datatable to load images - yui

I'm trying to create a data table that shows images in the status column. I followed some examples from stackoverflow but it doesn't work. Does anyone know how to get the image to load in the column? The code below works but it doesn't seem like fomatter function is doing anything.
<script src ="http://yui.yahooapis.com/3.13.0/build/yui/yui-min.js"></script>
<script>
(function() {
YUI().use("datatable-sort", function(Y) {
var cols = [
{key: "Status", label: "Health Status",
formatter: function(el, oRecord, oColumn, oData) {
if (oData){
el.innerHTML = '<img src="info.png">';
}
},
sortable: true},
{key: "Company", label: "Issue", sortable: true},
{key: "Phone", label: "Contact"},
{key: "Contact", label: "Name", sortable: true}
],
data = [
{Status: "123", Company: "Company Bee", Phone: "415-555-1234", Contact: "Sally Spencer"},
{Status: "123", Company: "Acme Company", Phone: "650-555-4444", Contact: "John Jones"},
{Status: "123", Company: "Industrial Industries", Phone: "408-555-5678", Contact: "Robin Smith"}
],
table = new Y.DataTable({
columns: cols,
data: data,
summary: "Contacts list",
caption: ""
}).render("#sort");
});
})();
</script>

instead of doing what I did, do the following:
{key: "Status", label: "Health Status", formatter:"<img src='{value}' >", allowHTML: true},...
It worked out!

Related

SuiteScript TypeError: Cannot read property "firstname" from undefined

I have a problem that's not making any sense to me. I have created a custom search and I am using the results from that search to addSelectOptions to a select field I have added.
However when trying to simply access a value within a nested object I am getting the error message: TypeError: Cannot read property "firstname" from undefined.
Here is the code:
var sfPlayersSearch = search
.create({
id: 'customsearch_pm_sf_players_search',
title: 'SF Players Search',
type: search.Type.EMPLOYEE,
columns: [
'entityid',
'firstname',
'lastname',
'custentity_pm_ws_sf_player',
],
filters: ['custentity_pm_ws_sf_player', 'is', 'true'],
})
.run()
.getRange(0, 100);
log.debug({ title: 'SF Players', details: sfPlayersSearch });
var player1ProxyField = form.addField({
id: 'custpage_pm_ws_sf_player_1_proxy',
label: 'Player 1 Proxy',
type: ui.FieldType.SELECT,
});
var player2ProxyField = form.addField({
id: 'custpage_pm_ws_sf_player_2_proxy',
label: 'Player 2 Proxy',
type: ui.FieldType.SELECT,
});
for (var i = 0; i < sfPlayersSearch.length; i++) {
log.debug({title: 'Result', details: sfPlayersSearch[i].values.firstname});
player1ProxyField.addSelectOption({ value: sfPlayersSearch[i], text: sfPlayersSearch[i].id });
}
JSON Object:
[
[
{
"recordType": "employee",
"id": "8",
"values": {
"entityid": "Artur X",
"firstname": "Artur",
"lastname": "X",
"custentity_pm_ws_sf_player": true
}
},
{
"recordType": "employee",
"id": "50",
"values": {
"entityid": "Darryl X",
"firstname": "Darryl",
"lastname": "X",
"custentity_pm_ws_sf_player": true
}
},
{
"recordType": "employee",
"id": "1983",
"values": {
"entityid": "Douglas X",
"firstname": "Douglas",
"lastname": "X",
"custentity_pm_ws_sf_player": true
}
},
{
"recordType": "employee",
"id": "86477",
"values": {
"entityid": "Paul X",
"firstname": "Paul",
"lastname": "X",
"custentity_pm_ws_sf_player": true
}
}
]
]
Any help greatly appreciated. I have tried doing .values || {}.firstname and this returns no error, but also no result.
Search.run().getRange() returns an array of Result objects. These are what you are iterating through in your for block. The Result object does not include values but rather includes methods for access the values getValue()) and text (getText()) of each result.
Change
log.debug({title: 'Result', details: sfPlayersSearch[i].values.firstname});.
to
log.debug({title: 'Result', details: sfPlayersSearch[i].getValue('firstname')});
While #krypton 's answer is correct for what you are doing you may find it useful to use Netsuite's JSONified version of search objects like what you see in your log.
If you were writing this as a library file where you might want to work in a Map/Reduce you can normalize the search result like
.getRange(0, 100)
.map(function(sr){
return JSON.parse(JSON.stringify(sr));
});
Now your original code for values.firstname would work.
Fun fact. If you are using SS 2.1 you can use let', const, and arrow functions:
const players = search.create()...
.getRange(0, 100)
.map(sr=>(JSON.parse(JSON.stringify(sr)));

Tabulator custom key bindings with .extendModule()

I'm trying to bind a custom keys combination to perform a custom action like below but the key binding is not working. I even tried adding keybindings: true in the init settings but no change. There are no errors, warnings or notices in the console whatsoever.
I'm really not sure whether I'm using the .extendModule() correctly, though I have checked the docs already.
var rowContextMenu = function(e, row) {
// do something here
console.log("RIGHT CLICK: Context menu triggered");
}
var deleteRow = function(row) {
let rData = row.getData();
if(rData.hasOwnProperty('_children')) {
let cRows = row.getTreeChildren();
$.each(cRows, function() {
let r = this;
setTimeout(function() {
deleteRow(r);
}, 0);
});
}
row.delete();
};
Tabulator.prototype.extendModule("keybindings", "actions", {
"deleteSelectedRows":function(){ //delete selected rows
let selectedRows = this.table.getSelectedRows();
selectedRows.forEach(function(row){
deleteRow(row);
});
console.log('ROWS DELETED: Triggered with button keyboard');
},
});
Tabulator.prototype.extendModule("keybindings", "bindings", {
deleteSelectedRows:"shift + 9",
});
let nestedData = [
{name:"Oli Bob", location:"United Kingdom", gender:"male", col:"red", dob:"14/04/1984", _children:[
{name:"Mary May", location:"Germany", gender:"female", col:"blue", dob:"14/05/1982"},
{name:"Christine Lobowski", location:"France", gender:"female", col:"green", dob:"22/05/1982"},
{name:"Brendon Philips", location:"USA", gender:"male", col:"orange", dob:"01/08/1980", _children:[
{name:"Margret Marmajuke", location:"Canada", gender:"female", col:"yellow", dob:"31/01/1999"},
{name:"Frank Harbours", location:"Russia", gender:"male", col:"red", dob:"12/05/1966"},
]},
]},
{name:"Jamie Newhart", location:"India", gender:"male", col:"green", dob:"14/05/1985"},
{name:"Gemma Jane", location:"China", gender:"female", col:"red", dob:"22/05/1982", _children:[
{name:"Emily Sykes", location:"South Korea", gender:"female", col:"maroon", dob:"11/11/1970"},
]},
{name:"James Newman", location:"Japan", gender:"male", col:"red", dob:"22/03/1998"},
];
let table = new Tabulator('#my-tabulator', {
height:"400px",
layout:"fitColumns",
data: nestedData,
/**
* // Actual ajax configuration that won't work with test data (works perfectly with live data)
*
* ajaxLoaderLoading:'<div class="text-center" style="display:inline-block;"><img style="width:100px;" src="/path/to/my/spinner.svg"></div>',
* ajaxURL:"/path/to/my/data.json", //ajax URL
* ajaxConfig:"get", //ajax HTTP request type
*/
sortable: false,
selectable:true, //make rows selectable
dataTree:true,
dataTreeChildIndent:24,
dataTreeStartExpanded:[true, false], //start with first level expanded, second level collapsed
dataTreeCollapseElement:"<span class='expand-collpase-btn'>-</span>",
dataTreeExpandElement:"<span class='expand-collpase-btn'>+</span>",
rowFormatter:function(row){
if(row.getData().parent_id === null){
row.getElement().classList.add("root-node");
}
},
keybindings: {
deleteSelectedRows:"shift + 9"
},
rowContext:rowContextMenu,
columnMinWidth : 24,
columns:[
{title:"Name", field:"name", width:200, responsive:0}, //never hide this column
{title:"Location", field:"location", width:150},
{title:"Gender", field:"gender", width:150, responsive:2}, //hide this column first
{title:"Favourite Color", field:"col", width:150},
{title:"Date Of Birth", field:"dob", align:"center", sorter:"date", width:150},
],
/**
* // Actual column configuration that won't work with test data (works perfectly with live data)
*
* columns:[
* {title:"Col 1", field:"field_1", headerSort:false, titleFormatter:headerFilter, titleFormatterParams:filters, responsive:0,
* formatter:function(cell, formatterParams){
* //cell - the cell component
* //formatterParams - parameters set for the column
*
* let rowData = cell.getRow().getData();
*
* if(rowData['test'] == 'String 1' || rowData['test'] === false) {
* let cellUrl = $('<a></a>', {href: '/path/to/cell/item/itemid:'+rowData['id'], target: "_blank"}).html(cell.getValue());
* return cellUrl[0];
* }
* return cell.getValue(); //return the contents of the cell;
* },
* },
* {title:"Col 2", field:"field_2", headerSort:false, width:150,
* formatter:function(cell, formatterParams){
* //cell - the cell component
* //formatterParams - parameters set for the column
*
* let rowData = cell.getRow().getData();
*
* if(rowData['test']) {
* return '<span class="text-muted text-bold text-italic">String 1</span>';
* }
* return '<span class="text-italic">String 2</span>';
* },
* },
* {title:"Col 3", headerSort:false, field:"field_3", width:200, align:"right", titleFormatter:headerFilter, titleFormatterParams:filters, responsive:2}, //hide this column first
* {title:"Col 4", headerSort:false, field:"field_4", width:200, align:"right", titleFormatter:headerFilter, titleFormatterParams:filters},
* {
* title:"",
* headerSort:false,
* resizable: false,
* columns: [
* {title:"", width:24, headerSort:false, resizable: false, formatter:editButton, cssClass:'table-actions'},
* {title:"", width:24, headerSort:false, resizable: false, formatter:deleteButton, cssClass:'table-actions'},
* ]
* },
* ]
*/
});
$('#delete-rows-btn').on('click', function(e){
let selectedRows = table.getSelectedRows();
selectedRows.forEach(function(row){
deleteRow(row);
});
console.log('ROWS DELETED: Triggered with button click');
});
$('#reload-table-btn').on('click', function(e){
console.log('Table reloaded');
table.replaceData(nestedData);
});
/**
* I'm using custom CSS
* but let's ignore it for the sake of this demo
*/
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/tabulator-tables#4.2.7/dist/css/tabulator.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/tabulator-tables#4.2.7/dist/css/bootstrap/tabulator_bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/tabulator-tables#4.2.7/dist/js/tabulator.min.js"></script>
<a id="delete-rows-btn" href="javascript:void(0);" class="btn btn-sm btn-danger">Delete Selected</a>
 
<a id="reload-table-btn" href="javascript:void(0);" class="btn btn-sm btn-primary">Reload Table</a>
<div id="my-tabulator" class="table-bordered"></div>
you need to use shift + keyCodeand disable rowSelectable. My code works if you
focus on table
press Shift + 9 Key
var rowContextMenu = function (e, row) {
// do something here
console.log("RIGHT CLICK: Context menu triggered");
}
var deleteRow = function (row) {
let rData = row.getData();
if (rData.hasOwnProperty('_children')) {
let cRows = row.getTreeChildren();
$.each(cRows, function () {
let r = this;
setTimeout(function () {
deleteRow(r);
}, 0);
});
}
row.delete();
};
Tabulator.prototype.extendModule("keybindings", "actions", {
"deleteSelectedRows": function () { //delete selected rows
let selectedRows = this.table.getSelectedRows();
selectedRows.forEach(function (row) {
deleteRow(row);
});
console.log('ROWS DELETED: Triggered with button keyboard');
},
});
Tabulator.prototype.extendModule("keybindings", "bindings", {
deleteSelectedRows: "shift + 9",
});
let nestedData = [
{
name: "Oli Bob", location: "United Kingdom", gender: "male", col: "red", dob: "14/04/1984", _children: [
{name: "Mary May", location: "Germany", gender: "female", col: "blue", dob: "14/05/1982"},
{name: "Christine Lobowski", location: "France", gender: "female", col: "green", dob: "22/05/1982"},
{
name: "Brendon Philips", location: "USA", gender: "male", col: "orange", dob: "01/08/1980", _children: [
{name: "Margret Marmajuke", location: "Canada", gender: "female", col: "yellow", dob: "31/01/1999"},
{name: "Frank Harbours", location: "Russia", gender: "male", col: "red", dob: "12/05/1966"},
]
},
]
},
{name: "Jamie Newhart", location: "India", gender: "male", col: "green", dob: "14/05/1985"},
{
name: "Gemma Jane", location: "China", gender: "female", col: "red", dob: "22/05/1982", _children: [
{name: "Emily Sykes", location: "South Korea", gender: "female", col: "maroon", dob: "11/11/1970"},
]
},
{name: "James Newman", location: "Japan", gender: "male", col: "red", dob: "22/03/1998"},
];
let table = new Tabulator('#my-tabulator', {
height: "400px",
layout: "fitColumns",
data: nestedData,
sortable: false,
// selectable: true, //make rows selectable
dataTree: true,
dataTreeChildIndent: 24,
dataTreeStartExpanded: [true, false], //start with first level expanded, second level collapsed
dataTreeCollapseElement: "<span class='expand-collpase-btn'>-</span>",
dataTreeExpandElement: "<span class='expand-collpase-btn'>+</span>",
rowFormatter: function (row) {
if (row.getData().parent_id === null) {
row.getElement().classList.add("root-node");
}
},
keybindings: {
deleteSelectedRows: "shift + 57"
},
rowContext: rowContextMenu,
columnMinWidth: 24,
columns: [
{title: "Name", field: "name", width: 200, responsive: 0}, //never hide this column
{title: "Location", field: "location", width: 150},
{title: "Gender", field: "gender", width: 150, responsive: 2}, //hide this column first
{title: "Favourite Color", field: "col", width: 150},
{title: "Date Of Birth", field: "dob", align: "center", sorter: "date", width: 150},
],
});
$('#delete-rows-btn').on('click', function (e) {
let selectedRows = table.getSelectedRows();
selectedRows.forEach(function (row) {
deleteRow(row);
});
console.log('ROWS DELETED: Triggered with button click');
});
$('#reload-table-btn').on('click', function (e) {
console.log('Table reloaded');
table.replaceData(nestedData);
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/tabulator-tables#4.2.7/dist/css/tabulator.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/tabulator-tables#4.2.7/dist/css/bootstrap/tabulator_bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/tabulator-tables#4.2.7/dist/js/tabulator.min.js"></script>
<a id="delete-rows-btn" href="javascript:void(0);" class="btn btn-sm btn-danger">Delete Selected</a>
 
<a id="reload-table-btn" href="javascript:void(0);" class="btn btn-sm btn-primary">Reload Table</a>
<div id="my-tabulator" class="table-bordered"></div>

Tabulator 4.2: sorter:"date" not working?

Even in the example given # the Tabulator site:
http://tabulator.info/basic/4.2
the date column does not sort, unlike the others. Is there a fix for that?
Date sorting for Tabulator is dependent on MomentJS.
Import Moment Js to your code
{title: "Date Of Birth", field: "dob", sorter:"date", sorterParams:{format:"DD/MM/YY"}},
Please check this Snippet
const tabledata1 = [
{id: 1, name: "Oli ", money: "0", col: "red", dob: "14/05/1982"},
{id: 2, name: "Mary ", money: "0", col: "blue", dob: "14/05/1982"},
{id: 3, name: "Christine ", money: "0", col: "green", dob: "22/05/1982"},
{id: 4, name: "Brendon ", money: "0", col: "orange", dob: "01/08/1980"},
{id: 5, name: "Margret ", money: "0", col: "yellow", dob: "31/01/1999"},
];
const table = new Tabulator("#example-table", {
height: 205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
data: tabledata1, //assign data to table
layout: "fitColumns", //fit columns to width of table (optional)
columns: [ //Define Table Columns
{title: "Name", field: "name", width: 150},
{
title: "money",
field: "money",
align: "left",
formatter: "money"
},
{title: "Favourite Color", field: "col"},
{title: "Date Of Birth", field: "dob", sorter:"date", sorterParams:{format:"DD/MM/YY"}},
]
});
function removeData() {
table.clearData();
}
function update() {
table.updateOrAddData(tabledata2);
// table.addData(tabledata2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://unpkg.com/tabulator-tables#4.2.4/dist/js/tabulator.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.2.4/dist/css/tabulator.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<div id="example-table"></div>

Selecting Row After Render/Table Load

I'm attempting to select a row within a Tabulator table once the data or table has been rendered/loaded. I'm not particularly fussed which callback is used, but when a user navigates to this page the table should load a predetermined record (which I will parse as a parameter).
The callback itself works well, as I can display a JS alert, however I'm still unable to select a line within Tabulator.
//create Tabulator on DOM element with id "example-table"
var table = new Tabulator(
"#example-table", {
height: (window.innerHeight), // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically
headerFilterPlaceholder: '', //default place holder text for filters
selectable: 1, //allows row within table to be selected and have selected state (not to be confused with row click function), can be set to have multiple selected (integer), true or false
data: [ **DATA1** ], //assign data to table
dataTree: true,
dataTreeStartExpanded: true,
dataTreeBranchElement: false, //adds or removes right angle leading from parent to child
dataTreeChildIndent: 25, //changes the indent padding
dataTreeCollapseElement: !1,
dataTreeStartExpanded: !0, //changes whether or not the entire table begins expanded
dataTreeCollapseElement: "<span>▼ </span>",
dataTreeExpandElement: "<span>► </span>",
layout: "fitColumns", //fit columns to width of table (optional)
columns: [ **COLUMN1** ],
rowClick:function(e, row) //triggered when the row is clicked
{
var scriptParam = **SCRIPTPARAM1**;
var rowId = row.getData().id;
var fieldName = **FIELDNAME1**;
var theList = [scriptParam, rowId, fieldName];
var doThis = "fmp://$/**FILE**?script=**SCRIPT1**&param=" + theList;
window.location.href = doThis;
},
rowDblClick:function(e, row) //triggered when the row is double clicked
{
table.selectRow(**ROWID**);
},
rowContext:function(e, row) //triggered when the row is right clicked
{
alert('right click');
e.preventDefault(); //overrides the browsers native right click function
},
cellEdited: function(cell)
{
var parameter = 1.1;
var distribute = cell.getColumn().getDefinition().distribute;
var id = cell.getData().id;
var table = cell.getColumn().getDefinition().fmTable;
var field = cell.getColumn().getDefinition().fmTable + "::" + cell.getColumn().getDefinition().fmField;
var table = cell.getColumn().getDefinition().fmTable;
var scriptBefore = cell.getColumn().getDefinition().script_before;
var scriptAfter = cell.getColumn().getDefinition().script_after;
var value = cell.getValue();
var theList = [parameter, distribute, id, table, field, value];
var doThis = "fmp://$/**FileName**?script=**ScriptName**&param=" + theList;
window.location.href = doThis;
},
rowFormatter: function(row) {
var rowColor = row.getData().color
row.getElement().style.backgroundColor = rowColor;
},
renderComplete:function()
{
table.selectRow(**ROWID**);
}
}
);
I'm expecting that once the page is loaded, the row I defined as **ROWID** (which for my testing is ID 1) is selected. FYI, the double click function (regardless of which row is clicked) performs as expected, selecting the correct row.
To further this, I'm looking to (at times) select a child row of the data tree, for example:
const tabledata1 = [{
id: "1",
name: "Oli Bob",
location: "United Kingdom",
gender: "male",
col: "red",
dob: "14/04/1984",
_children: [{
id: "2",
name: "Mary May",
location: "Germany",
gender: "female",
col: "blue",
dob: "14/05/1982"
},
{
name: "Christine Lobowski",
location: "France",
gender: "female",
col: "green",
dob: "22/05/1982"
},
{
name: "Brendon Philips",
location: "USA",
gender: "male",
col: "orange",
dob: "01/08/1980",
_children: [{
name: "Margret Marmajuke",
location: "Canada",
gender: "female",
col: "yellow",
dob: "31/01/1999"
},
{
name: "Frank Harbours",
location: "Russia",
gender: "male",
col: "red",
dob: "12/05/1966"
},
]
},
]
},
{
name: "Jamie Newhart",
location: "India",
gender: "male",
col: "green",
dob: "14/05/1985"
},
{
name: "Gemma Jane",
location: "China",
gender: "female",
col: "red",
dob: "22/05/1982",
_children: [{
name: "Emily Sykes",
location: "South Korea",
gender: "female",
col: "maroon",
dob: "11/11/1970"
}, ]
},
{
name: "James Newman",
location: "Japan",
gender: "male",
col: "red",
dob: "22/03/1998"
},
];
const table = new Tabulator("#example-table", {
height: 205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
data: tabledata1, //assign data to table
selectable: true, //make rows selectable
layout: "fitColumns", //fit columns to width of table (optional)
autoColumns: true,
dataTree: true,
dataTreeStartExpanded: true,
renderComplete: function() {
console.log('done');
this.selectRow(2);
}
});
table.selectRow(ROWID); wont work until table is initialized you
have to do this.selectRow
Check this jsfiddle
renderComplete: function() {
const rows = this.getRows();
console.log('rows', rows);
for (let i = 0; i < rows.length; i++) {
const childRows = rows[i].getTreeChildren();
if (childRows.length > 0) {
// console.log('childRows', childRows);
// this.selectRow(childRows);
for (let j = 0; j < childRows.length; j++) {
const gender = childRows[j].getData().gender;
console.log('gender', gender);
if (gender === 'male') {
this.selectRow(childRows[j]);
const childRows2 = childRows[j].getTreeChildren();
}
}
}
}
}
});

Export To Excel filtered data with Free jqgrid 4.15.4 in MVC

I have a question regarding Export to Excel in free-jqgrid 4.15.4. I want to know how to use this resultset {"groupOp":"AND","rules":[{"field":"FirstName","op":"eq","data":"Amit"}]} into my Business Logic Method.
Just for more clarification, I've using OfficeOpenXml and if I don't use filtered resultset(aforementioned) it is working fine and I'm able to download file with full records in an excel sheet. But I'm not sure what to do or how to utilize the resultset {"groupOp":"AND","rules":[{"field":"FirstName","op":"eq","data":"Amit"}]}
If required I can share my controller and BL code.
I have added a fiddle which shows implementation of Export to Excel button in jqGrid pager.
Before coming to here, I've read and tried to understand from following questions:
1] jqgrid, export to excel (with current filter post data) in an asp.net-mvc site
2] Export jqgrid filtered data as excel or CSV
Here is the code :
$(function () {
"use strict";
var mydata = [
{ id: "10", FirstName: "test", LastName: "TNT", Gender: "Male" },
{ id: "11", FirstName: "test2", LastName: "ADXC", Gender: "Male" },
{ id: "12", FirstName: "test3", LastName: "SDR", Gender: "Female" },
{ id: "13", FirstName: "test4", LastName: "234", Gender: "Male" },
{ id: "14", FirstName: "test5", LastName: "DAS", Gender: "Male" },
];
$("#list").jqGrid({
data: mydata,
colNames: ['Id', 'First Name', 'Last Name', 'Gender'],
colModel: [
{
label: "Id",
name: 'Id',
hidden: true,
search: false,
},
{
label: "FirstName",
name: 'FirstName',
searchoptions: {
searchOperators: true,
sopt: ['eq', 'ne', 'lt', 'le','ni', 'ew', 'en', 'cn', 'nc'],
}, search: true,
},
{
label: "LastName",
name: 'LastName',
searchoptions: {
searchOperators: true,
sopt: ['eq', 'ne', 'lt', 'ni', 'ew', 'en', 'cn', 'nc'],
}, search: true,
},
{
label: "Gender",
name: 'Gender',
search: true, edittype: 'select', editoptions: { value: 'Male:Male;Female:Female' }, stype: 'select',
},
],
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list').restoreRow(lastsel);
jQuery('#list').editRow(id, true);
lastsel = id;
}
},
loadComplete: function (id) {
if ($('#list').getGridParam('records') === 0) {
//$('#grid tbody').html("<div style='padding:6px;background:#D8D8D8;'>No records found</div>");
}
else {
var lastsel = 0;
if (id && id !== lastsel) {
jQuery('#list').restoreRow(lastsel);
jQuery('#list').editRow(id, true);
lastsel = id;
}
}
},
loadonce: true,
viewrecords: true,
gridview: true,
width: 'auto',
height: '150px',
emptyrecords: "No records to display",
iconSet:'fontAwesome',
pager: true,
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "Id"
},
});
jQuery("#list").jqGrid("navButtonAdd", {
caption: "",
buttonicon: "fa-table",
title: "Export To Excel",
onClickButton: function (e) {
var projectId = null;
var isFilterAreUsed = $('#grid').jqGrid('getGridParam', 'search'),
filters = $('#grid').jqGrid('getGridParam', 'postData').filters;
var Urls = "/UsersView/ExportToExcel_xlsxFormat?filters="+ encodeURIComponent(filters); //' + encodeURIComponent(filters);/
if (totalRecordsCount > 0) {
$.ajax({
url: Urls,
type: "POST",
//contentType: "application/json; charset=utf-8",
data: { "searchcriteria": filters, "projectId": projectId, "PageName": "MajorsView" },
//datatype: "json",
success: function (data) {
if (true) {
window.location = '/UsersView/SentFiletoClientMachine?file=' + data.filename;
}
else {
$("#resultDiv").html(data.errorMessage);
$("#resultDiv").addClass("text-danger");
}
},
error: function (ex) {
common.handleAjaxError(ex.status);
}
});
}
else {
bootbox.alert("There are no rows to export in the Participant List")
if (dialog) {
dialog.modal('hide');
}
}
}
});
});
https://jsfiddle.net/ap43xecs/10/
There are exist many option to solve the problem. The simplest one consist of sending ids of filtered rows to the server instead of sending filters parameter. Free jqGrid supports lastSelectedData parameter and thus you can use $('#grid').jqGrid('getGridParam', 'lastSelectedData') to get the array with items sorted and filtered corresponds to the current filter and sorting criteria. Every item of the returned array should contain Id property (or id property) which you can use on the server side to filter the data before exporting.
The second option would be to implement server side filtering based on the filters parameter, which you send currently to the server. The old answer (see FilterObjectSet) provides an example of filtering in case of usage Entity Framework. By the way, the answer and another one contain code, which I used for exporting grid data to Excel using Open XML SDK. You can compare it with your existing code.
In some situations it could be interesting to export grid data to Excel without writing any server code. The corresponding demo could be found in the issue and UPDATED part of the answer.

Resources