I imported my tabulator.js from template using webpack.min.js I added .js("resources/js/tabulator.js", "dist/js") to my webpack.min.js, and run npm run dev
then I imported my <script src="{{ asset('dist/js/tabulator.js') }}"></script> bellow <script src="{{ asset('dist/js/app.js') }}"></script>
but as soon I imported it, i got errors <script src="{{ asset('dist/js/tabulator.js') }}"></script> from both app.js and tabulator.js but i kept going since it was working just fine
but then i notice my filters are not working, when i try to type on console table.setFilter() or table.download() it isn't working. below is my js
if ($("#role-tabulator").length) {
// Setup Tabulator
let table = new Tabulator("#role-tabulator", {
ajaxURL: "/role",
ajaxFiltering: true,
ajaxSorting: true,
printAsHtml: true,
printStyled: true,
pagination: "remote",
paginationSize: 10,
paginationSizeSelector: [10, 20, 30, 40, 50],
layout: "fitColumns",
responsiveLayout: "collapse",
placeholder: "No matching records found",
columns: [
{
formatter: "responsiveCollapse",
width: 40,
minWidth: 30,
hozAlign: "center",
resizable: false,
headerSort: false,
},
// For HTML table
{
title: "NAME",
minWidth: 200,
responsive: 0,
field: "name",
vertAlign: "middle",
print: false,
download: false,
formatter(cell, formatterParams) {
return `<div>
<div class="font-medium whitespace-nowrap">${
cell.getData().name
}</div>
</div>`;
},
},{
title: "ACTIONS",
minWidth: 200,
field: "actions",
responsive: 1,
hozAlign: "center",
vertAlign: "middle",
print: false,
download: false,
formatter(cell, formatterParams) {
let a =
$(`<div class="flex lg:justify-center items-center">
<a class="edit flex items-center mr-3" href="javascript:;">
<i data-lucide="check-square" class="w-4 h-4 mr-1"></i> Edit
</a>
<a class="delete flex items-center text-danger" href="javascript:;">
<i data-lucide="trash-2" class="w-4 h-4 mr-1"></i> Delete
</a>
</div>`);
$(a)
.find(".edit")
.on("click", function () {
alert("EDIT");
});
$(a)
.find(".delete")
.on("click", function () {
alert("DELETE");
});
return a[0];
},
},
// For print format
{
title: "NAME",
field: "name",
visible: false,
print: true,
download: true,
},
],
renderComplete() {
createIcons({
icons,
"stroke-width": 1.5,
nameAttr: "data-lucide",
});
},
});
// Redraw table onresize
window.addEventListener("resize", () => {
table.redraw();
createIcons({
icons,
"stroke-width": 1.5,
nameAttr: "data-lucide",
});
});
// Filter function
function filterHTMLForm() {
let field = $("#role-tabulator-html-filter-field").val();
let type = $("#role-tabulator-html-filter-type").val();
let value = $("#role-tabulator-html-filter-value").val();
table.setFilter(field, type, value);
}
// On submit filter form
$("#role-tabulator-html-filter-form")[0].addEventListener(
"keypress",
function (event) {
let keycode = event.keyCode ? event.keyCode : event.which;
if (keycode == "13") {
event.preventDefault();
filterHTMLForm();
}
}
);
// On click go button
$("#role-tabulator-html-filter-go").on("click", function (event) {
filterHTMLForm();
});
// On reset filter form
$("#role-tabulator-html-filter-reset").on("click", function (event) {
$("#role-tabulator-html-filter-field").val("name");
$("#role-tabulator-html-filter-type").val("like");
$("#role-tabulator-html-filter-value").val("");
filterHTMLForm();
});
// Export
$("#role-tabulator-export-csv").on("click", function (event) {
table.download("csv", "data.csv");
});
$("#role-tabulator-export-json").on("click", function (event) {
table.download("json", "data.json");
});
$("#role-tabulator-export-xlsx").on("click", function (event) {
window.XLSX = xlsx;
table.download("xlsx", "data.xlsx", {
sheetName: "Products",
});
});
$("#role-tabulator-export-html").on("click", function (event) {
table.download("html", "data.html", {
style: true,
});
});
// Print
$("#role-tabulator-print").on("click", function (event) {
table.print();
});
}
Related
The AJAX code works fine and creates my desired outputs and on "success"
success: function (data) {
console.log(data);
$( "#gridjs_table" ).load(window.location.href + " #gridjs_table" );//updates the gridjs_table div
}
Gridjs Table works fine as well
<script src="https://cdn.jsdelivr.net/npm/gridjs/dist/gridjs.umd.js"></script>
<link href="https://cdn.jsdelivr.net/npm/gridjs/dist/theme/mermaid.min.css" rel="stylesheet"/>
<div id="gridjs_table">
<div id="wrapper"></div>
<script>
new gridjs.Grid({
columns: [
{ name: "Title",
formatter: (cell, row) => {
return gridjs.html(`<span style='text-align: center;' id='visible_title'>${row.cells[0].data}</span>`);
}},
{ name: "src", hidden: true},
{ name: "Cover",
sort:{enabled: false},
formatter: (cell, row) => {
return gridjs.html(`<div style='text-align: center;'><img id="cover" src="../library/${row.cells[1].data}" alt="no"></div>`);
}
},
{ name: "Link", sort:{enabled: false},
formatter: (cell, row) => {
return gridjs.html(`<div id='link_format'><span id='visible_link'>${row.cells[3].data}</span><br><a href='${row.cells[3].data}' target='_blank'><div id='visit'>Visit</div></a></div>`);
}},
{ name: "Status"},
{ name: "Views"},
{ name: "Stars" },
{ name: "Bookmarked"},
{ name: "Action",
sort:{enabled: false},
formatter: (cell, row) => {
return gridjs.html(`<a href='edit.php?file=${row.cells[2].data}' onclick="window.open('edit.php?file=${row.cells[2].data}',
'newwindow',
'width=300,height=250');
return false;"><div id='edit'>Edit</div></a>
<a href='../library/view.php?view=${row.cells[2].data}' onclick="window.open('../library/view.php?view=${row.cells[2].data}',
'newwindow',
'width=320,height=580');
return false;" target='_blank'><div id='mobile'>Mobile</div></a>
`);
}
}
],
data: [
<?php
echo $data_implode;
?>
],
sort: true,
search: {
enabled: true,
debounceTimeout: 500,
},
style: {
table: {
border: '3px solid #ccc',
},
},
fixedHeader: true,
pagination: {
enabled: true,
limit: 3
}
}).render(document.getElementById("wrapper"));
</script>
</div>
</div>
On success, the ajax should refresh the table but it's not working. It just went blank, no display, the whole table is gone. Refreshing the whole page works and displays the newly added items but I don't want that.
Refreshing the div holding the table does not work so I ended up using this code and it worked.
$('body').load('dashboard.php');
I'm trying to hide a button. If it was on the html i would simply do
<security:authorize access="hasAuthority('Administrator')">
//html button code
</security:authorize>
but my delete button is being generated from datatable.
var table = $('#dataTable').DataTable({
language: {
searchPlaceholder: "Search...",
emptyTable: "There are no available flows."
},
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
},
{type: "date-euro", targets: 7},
{type: "date-euro", targets: 8}
],
order: [[1, 'desc']],
select: {
style: 'multi',
selector: 'td:first-child'
},
lengthChange: false,
dom: 'Bfrtip',
buttons: [
{
text: '<span class="fa fa-plus"></span> Create',
className: 'btn-primary-outline',
action: function () {
location.href = "create-flow";
}
},
{
text: '<span class="fa fa-trash"></span> Delete',
className: 'btn-danger-outline',
action: function () {
console.log($('#hasAuthority').val());
var selectedRows = table.rows({selected: true});
if (selectedRows.nodes().length > 0) {
//Get names
var data = selectedRows.data();
var names = [];
$.each(data, function (index, value) {
names.push(value[2]);
});
//Remove them
$.ajax({
url: '/flow/delete?names=' + names,
type: 'delete',
success: function () {
//reload page
location.reload();
}
});
//de-select selected rows
table.rows('.selected').deselect();
}
}
}
]
});
I'm trying to give a value to a input if user is admin or not but I'm getting undefined
<security:authorize access="hasAuthority('Administrator')" var="hasAuthority"></security:authorize>
<input type="hidden" id="hasAuthority" value="${hasAuthority}">
But then how do I corporate the if(hasAuthority) only on the delete button? The syntax doesn't match.
Hi I have a Grid that is using cell edit and Inline editing. It saves to the ClientArray
$('#list').jqGrid({
datatype: "local",
colNames: ["Parameter Id", "Parameter Name", 'Parameter Value'],
colModel: [
{ name: "Id", index: "Id", align: "left", key: true, editable: false,hidden:true, jmap: 0 },
{ name: "ParameterName", index: "ParameterName", align: "left", editable: false, jmap: 1 },
{ name: "ParameterValue", index: "ParameterValue", align: "left", editable: true, edittype: "text", editoptions: { maxlength: 100 }, editrules: {required: true }, jmap: 2 }
],
pager: "#pager",
rowNum: 100,
rowList: [],
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: true, // disable current view record text like 'View 1-10 of 100'
height: '100%',
scrollOffset: 0,
sortname: "Name",
sortorder: "Asc",
gridview: true,
caption: 'Parameters',
autowidth: true,
hidegrid: false,
loadonce: true,
//beforeEditCell: function () {
// $("#list_ilsave").removeClass('ui-state-disabled');
// return;
//},
//afterEditCell: function (rowid, cellname, value, iRow, iCol) {
// $('#list').jqGrid('getCell', rowid, iCol).focus();
// return;
//},
width: totalWidth,
cellEdit: true,
cellsubmit: "clientArray"
});
$('#list').jqGrid('inlineNav', '#pager', {
edit: false,
add: false,
del: false,
save: true,
savetext: 'Save',
cancel: false
});
When I edit a Cell the save button remains disabled. If I manually Enable the button in beforeCellEdit, the editable cell hasn't got focus until you select another cell. This behavior is only happening in IE.
I have tried to fix both these issues individually in my commented out code, and I have found that the loss of focus is caused by the line
$("#list_ilsave").removeClass('ui-state-disabled');
I tried placing this line in beforeEditCell and in afterEditCell and it causes the input field to loose focus.
I was using JQ Grid 4.4.4 and I have tried updating to 4.6.0 after I read there were updates to Inline Editing after 4.4.4
UPDATE
I have changed my grid to use onSelectRow
onSelectRow: function (rowid) {
var $grid = $('#list');
var iRow = $("#" + rowid)[0].rowIndex;
$grid.jqGrid('editRow', rowid, {
keys: true,
oneditfunc: function(rowid, response) {
var $saveButton = $("#list_ilsave");
if ($saveButton.hasClass('ui-state-disabled')) {
$saveButton.removeClass('ui-state-disabled');
}
markCellAsDirty(rowid, $grid);
return true;
},
successfunc: function() {
alert('success');
return true;
},
aftersavefunc: function() {
alert('after save');
return true;
},
errorfunc: function() {
alert('error');
return true;
}
});
},
cellsubmit: "clientArray"
But I can't get any of the editRow events to fire other than oneditfunc. I also have an issue with getting the changed cells.
This method marks the cells as dirty / edited
function markCellAsDirty(rowid, grid) {
$(grid.jqGrid("setCell", rowid, "ParameterValue", "", "dirty-cell"));
$(grid[0].rows.namedItem(rowid)).addClass("edited");
}
I try to get the edited cells as follows
var editedRows = $grid.getChangedCells('dirty');
Before posting editedRows in an AJAX method to my server.
I'm not sure what you want to implement exactly, but I modified your demo to the following https://jsfiddle.net/OlegKi/byygepy3/11/. I include the full JavaScript code of the demo below
$(function () {
var myData = [
{ id: 10, ParameterName: "Test", ParameterValue: "" },
{ id: 20, ParameterName: "Test 1", ParameterValue: "" },
{ id: 30, ParameterName: "Test 2", ParameterValue: "" }
],
$grid = $("#list");
// change the text displayed on editrules: {required: true }
$.extend(true, $.jgrid.locales["en-US"].edit.msg, {
required: "No value was entered for this parameter!!!"
});
$grid.jqGrid({
datatype: "local",
data: myData,
colNames: ["", "Parameter Name", "Parameter Value"],
colModel: [
{ name: "act", template: "actions" }, // optional feature
{ name: "ParameterName" },
{ name: "ParameterValue", editable: true,
editoptions: { maxlength: 100 }, editrules: {required: true } }
],
cmTemplate: { autoResizable: true },
autoResizing: { compact: true },
pager: true,
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: true, // disable current view record text like 'View 1-10 of 100'
sortname: "Name",
iconSet: "fontAwesome",
caption: 'Parameters',
autowidth: true,
hidegrid: false,
inlineEditing: {
keys: true
},
singleSelectClickMode: "selectonly", // prevent unselect once selected rows
beforeSelectRow: function (rowid) {
var $self = $(this), i,
// savedRows array is not empty if some row is in inline editing mode
savedRows = $self.jqGrid("getGridParam", "savedRow");
for (i = 0; i < savedRows.length; i++) {
if (savedRows[i].id !== rowid) {
// save currently editing row
// one can replace saveRow to restoreRow in the next line
$self.jqGrid("saveRow", savedRows[i].id);
}
}
return savedRows.length === 0; // allow selection if saving successful
},
onSelectRow: function (rowid) {
$(this).jqGrid("editRow", rowid);
},
afterSetRow: function (options) {
var item = $(this).jqGrid("getLocalRow", options.rowid);
if (item != null) {
item.dirty = true;
}
},
navOptions: {
edit: false,
add: false,
search: false,
deltext: "Delete",
refreshtext: "Refresh"
},
inlineNavOptions: {
save: true,
savetext: "Save",
cancel: false,
restoreAfterSelect: false
},
formDeleting: {
// delete options
url: window.g_baseUrl + 'MfgTransactions_MVC/COA/Delete?',
beforeSubmit: function () {
// get value
var selRowId = $(this).jqGrid('getGridParam', 'selrow');
var parametricValue = $(this).jqGrid('getCell', selRowId, 'ParameterValue');
// check if empty
if (parametricValue === "") {
return [false, "Cannot delete: No value exists for this parameter"];
}
return [true, "Successfully deleted"];
},
delData: {
batchId: function () {
return $("#BatchId").val();
}
},
closeOnEscape: true,
closeAfterDelete: true,
width: 400,
msg: "Are you sure you want to delete the Parameter?",
afterComplete: function (response) {
if (response.responseText) {
alert("response.responseText");
}
//loadBatchListIntoGrid();
}
}
}).jqGrid('navGrid')
.jqGrid('inlineNav')
.jqGrid('navButtonAdd', {
caption: "Save Changed",
buttonicon: "fa-floppy-o",
onClickButton: function () {
var localData = $(this).jqGrid("getGridParam", "data"),
dirtyData = $.grep(localData, function (item) {
return item.dirty;
});
alert(dirtyData.length > 0 ? JSON.stringify(dirtyData) : "no dirty data");
}
});
// make more place for navigator buttons be rwducing the width of the right part
var pagerIdSelector = $grid.jqGrid("getGridParam", "pager");
$(pagerIdSelector + "_right").width(100);
// make the grid responsive
$(window).bind("resize", function () {
$grid.jqGrid("setGridWidth", $grid.closest(".container-fluid").width());
}).triggerHandler("resize");
});
where HTML code is
<div class="container-fluid">
<div class="row">
<div id="gridarea" class="col-md-6 col-md-offset-3">
<table id="list"></table>
</div>
</div>
</div>
and CSS code
.ui-th-column>div, .ui-jqgrid-btable .jqgrow>td {
word-wrap: break-word; /* IE 5.5+ and CSS3 */
white-space: pre-wrap; /* CSS3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
overflow: hidden;
vertical-align: middle;
}
It demonstrate how one can implement starting inline editing on select row. Additionally I added optional column with template: "actions" which can be alternative implementation. I set property dirty in every item of data inside of afterSetRow callback and I added "Save Changed" button, which uses localData = $(this).jqGrid("getGridParam", "data") and dirtyData = $.grep(localData, function (item) { return item.dirty; }); to get the dirty (modified) data.
I am trying to give a list in a popup according to Ajax request. Before Ajax request , list is in popup but after Ajax request, list stay in the page instead of popup and also there is the old list in the popup window. Here is the codes
<script>
function CreateMap() {
var chart = AmCharts.makeChart("piechartdiv", {
"type": "pie",
"theme": "light",
"fontFamily":"Calibri",
"dataProvider": [{
"product":"Following",
"value": #following,
"color": "#009688"
}, {
"product":"Not Following",
"value": #notFollowing ,
"color": "#555555"
}],
"legend": {
"align" : "right",
"fontSize" : 14
},
"marginLeft":-100,
"marginTop":-45,
"marginBottom":0,
"labelsEnabled":false,
"colorField": "color",
"valueField": "value",
"titleField": "product",
"outlineAlpha": 0.4,
"depth3D": 15,
"balloonText": "[[title]]<br><span style='font-size:14px'><b>[[value]]</b> ([[percents]]%)</span>",
"angle": 20,
"export": {
"enabled": true
}
});
jQuery('.chart-input').off().on('input change', function () {
var property = jQuery(this).data('property');
var target = chart;
var value = Number(this.value);
chart.startDuration = 0;
if (property == 'innerRadius') {
value += "%";
}
target[property] = value;
chart.validateNow();
});
chart.addListener("clickSlice", function (event) {
if ( event.dataItem.title == 'Unfollowing')
{
document.getElementById("s_open").click();
}
});
}
var isAjax = #isAjax;
if(isAjax)
{
CreateMap();
}
else
{
AmCharts.ready(function () {
CreateMap();
});
}
}
<button id="s_open" class="s_open btn-default" style="display:none;">Open popup</button>
<div id="s_follow">
<div class="row" style="border-radius:5px; padding:20px; background-color:#fff;">
<table id="hostTable" class="table table-striped" cellspacing="0">
<thead>
<tr>
<th>Host Table</th>
</tr>
</thead>
<tbody>
#Html.Raw(comparedDataTable.ToString())
</tbody>
</table>
<button class="btn s_close btn-danger">Close</button>
</div>
<script>
$(document).ready(function () {
$('#hostTable').DataTable( {
dom: 'Bfrtip',
buttons: [
'excelHtml5',
'csvHtml5'
],
destroy: true,
} );
});
$(document).ready(function () {
// Initialize the plugin
$('#s_follow').popup({
color: 'black',
opacity: 0.5,
transition: '0.3s',
scrolllock: true
});
});
How can we put the list hostTable into popup after ajax request?
SOLUTION
Use onopen option to initialize the table, see the code below.
$(document).ready(function () {
$('#s_follow').popup({
color: 'black',
opacity: 0.5,
transition: '0.3s',
scrolllock: true,
vertical: "top",
onopen: function() {
// If table was initialized before
if ($.fn.DataTable.isDataTable('#hostTable')){
// Clear table
$('#hostTable').DataTable().clear();
}
$('#hostTable').DataTable( {
dom: 'Bfrtip',
buttons: [
'excelHtml5',
'csvHtml5'
],
destroy: true
});
}
});
});
DEMO
See this jsFiddle for code and demonstration.
In a custom button in my pager, I call grid.jqGrid("getGridParam", "data"), "data") to get all the data in the grid but it returns empty array. When I call grid.jqGrid("getGridParam", "data") in the loadComplete function, it still returns an empty array. However if I call grid.jqGrid('getRowData') it gives me the data I am looking for. See my code below.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/css/jquery-ui.min.css"/>
<link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/css/ui.jqgrid.css"/>
<!-- Overide css styling to ensure that calendar image is inline with text box -->
<style type="text/css">.ui-jqgrid .ui-search-table .ui-search-input > input,
.ui-jqgrid .ui-search-table .ui-search-input > select,
.ui-jqgrid .ui-search-table .ui-search-input > img {vertical-align: middle; display: inline-block;}
</style>
<script src="${pageContext.request.contextPath}/js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/js/jquery-ui.min.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/js/grid.locale-en.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<title>Trucks Overview</title>
<script type="text/javascript">
jQuery().ready(function () {
var grid = jQuery("#truck_grid");
var orderGridDialog = $('#truck_grid_dialog');
var gridData;
getUniqueNames = function(columnName) {
var texts = grid.jqGrid('getCol', columnName, false);
var uniqueTexts = [], textsLength = texts.length, text, i, textsMap = {};
for (i=0;i<textsLength;i++) {
text = texts[i];
if (text != undefined && textsMap[text] === undefined) {
// to test whether the texts is unique we place it in the map.
textsMap[text] = true;
uniqueTexts.push(text);
}
}
return uniqueTexts;
};
buildSearchSelect = function(uniqueNames) {
var values=":All";
$.each (uniqueNames, function() {
values += ";" + this + ":" + this;
});
return values;
};
setSearchSelect = function(columnName) {
grid.jqGrid('setColProp', columnName,
{ stype: 'select',
searchoptions: {
value:buildSearchSelect(getUniqueNames(columnName)),
sopt:['eq']
}
}
);
};
var initDateWithButton = function (elem) {
if (/^\d+%$/.test(elem.style.width)) {
// remove % from the searching toolbar
elem.style.width = '';
}
// to be able to use 'showOn' option of datepicker in advance searching dialog
// or in the editing we have to use setTimeout
setTimeout(function () {
$(elem).datepicker({
dateFormat: 'mm/dd/yy',
showOn: 'button',
changeYear: true,
changeMonth: true,
buttonImageOnly: true,
buttonImage: "images/calendar.gif",
buttonText: "Select date",
showButtonPanel: true,
onSelect: function (dateText, inst) {
inst.input.focus();
if (typeof (inst.id) === "string" && inst.id.substr(0, 3) === "gs_") {
$(inst.id).val(dateText);
grid[0].triggerToolbar();
}
else {
// to refresh the filter
$(inst).trigger("change");
}
}
});
}, 100);
};
grid.jqGrid({
url: '${pageContext.request.contextPath}/getTrucksJSONAction',
datatype: "json",
mtype: 'GET',
colNames: ['Truck ID', 'Status', 'Carrier Code', 'Date Created', 'Date Closed', 'T1 Status', 'Truck Arrived'],
colModel: [
{name: 'truckId', key:true, index: 'truckId', align: 'center', width: 100},
{name: 'status', index: 'status', align: 'center', width: 100},
{name: 'carrierName', index: 'carrierName', align: 'center', width: 100},
{name: 'createdDate', index: 'createdDate', align: 'center', width: 100},
{name: 'closedDate', index: 'closedDate', align: 'center', width: 100},
{name: 't1Status', sortable: false, align: 'center', width: 100, fixed: true,
formatter: function (celvalue) {
return celvalue ?
"<img src='http://www.clker.com/cliparts/q/j/I/0/8/d/green-circle-icon-md.png' alt='green light' style='width:15px;height:15px'/>" :
"<img src='http://www.iconsdb.com/icons/preview/red/circle-xxl.png' alt='red light' style='width:10px;height:10px'/>";
}} ,
{name: 'truckArrived', sortable: false, align: 'center', width: 100, fixed: true,
formatter: function (celvalue) {
return celvalue ?
"<img src='http://www.clker.com/cliparts/q/j/I/0/8/d/green-circle-icon-md.png' alt='green light' style='width:15px;height:15px'/>" :
"<img src='http://www.iconsdb.com/icons/preview/red/circle-xxl.png' alt='red light' style='width:10px;height:10px'/>";
}}
],
rowNum: 10,
height: 300,
autoheight: true,
autowidth: true,
rowList: [10, 20, 30],
pager: jQuery('#truck_grid_pager'),
sortname: 'truckId',
sortorder: "desc",
jsonReader: {
root: "records",
page: "page",
total: "total",
records: "rows",
repeatitems: false
},
viewrecords: true,
altRows: false,
gridview: true,
hidegrid: false,
multiselect:true,
recordtext: '',
emptyrecords: 'No Trucks',
forceFit: true,
caption: "Trucks Overview",
loadComplete: function() {
// Reload the grid after changing paginattion
var allRecords = grid.getGridParam('lastpage') * grid.getGridParam('records');
grid.jqGrid('setGridParam', {
recordtext: allRecords + ' Trucks(s) Found. Displaying {0} to {1}'});
$(this).trigger("reloadGrid");
async: false,
setSearchSelect('status');
setSearchSelect('carrierName');
grid.jqGrid('setColProp', 'truckId', {
searchoptions : {
sopt : [ 'bw' ],
dataInit : function(elem) {
$(elem).autocomplete({
source : getUniqueNames('truckId'),
delay : 0,
minLength : 0
});
}
}
});
grid.jqGrid('setColProp', 'createdDate', {
sorttype: 'date', editable: true,
editoptions: { dataInit: initDateWithButton, size: 8 },
searchoptions: {
sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
dataInit: initDateWithButton
}
});
gridData = $(this).jqGrid("getGridParam", "data");
grid.jqGrid('filterToolbar', {autoSearch: true});
},
}).navGrid('#truck_grid_pager', {edit: false, add: false, del: false, search: false, refresh: true})
.navButtonAdd('#truck_grid_pager', {caption:"Truck Arrived", buttonicon:"ui-icon-flag", position:"first", title:"Truck Arrived",
onClickButton: function(){
var i;
var data = grid.jqGrid("getGridParam", "data");
var selRowIds = grid.jqGrid('getGridParam', 'selarrrow');
for (i = 0; i < data.length; i++) {
if (selRowIds.indexOf(data[i].truckId) > -1) {
data[i].truckArrived = true;
}
}
grid.trigger("reloadGrid");
}
})
.navButtonAdd('#truck_grid_pager', {caption:"Ship Confirm", buttonicon:"ui-icon-circle-check", position:"first", title:"Ship Confirm",
onClickButton: function(){
alert("Ship has been confirmed");}
});
orderGridDialog.dialog({
autoOpen: false,
width: 1000,
height: 400,
draggable: false,
show: {
effect: "blind",
duration: 500
},
hide: {
effect: "blind",
duration: 250
},
close: function(event, ui){
orderGridDialog.text('Loading Grid...');
}
});
});
</script>
</head>
<body>
<table id="truck_grid"></table>
<div id="truck_grid_pager"></div>
<div id="truck_grid_dialog" title="Orders Overview">Loading...</div>
</body>
</html>
The problem happens in the last section of the code, namely:
.navButtonAdd('#truck_grid_pager', {caption:"Truck Arrived", buttonicon:"ui-icon-flag", position:"first", title:"Truck Arrived",
onClickButton: function(){
var i;
var data = grid.jqGrid("getGridParam", "data");
var selRowIds = grid.jqGrid('getGridParam', 'selarrrow');
for (i = 0; i < data.length; i++) {
if (selRowIds.indexOf(data[i].truckId) > -1) {
data[i].truckArrived = true;
}
}
grid.trigger("reloadGrid");
}
})
The second problem I have is when grid.trigger("reloadGrid") is called, the truckArrived icon is not changed from red to green as expected.
The internal parameter data will be used only if one uses datatype: "local". You use datatype: "json". It means that the server hold whole dataset only. The url: '${pageContext.request.contextPath}/getTrucksJSONAction' receive request for the page of sorted and filtered data. The server should implement sorting, filtering/sorting and paging.
There exists a special case: one use remote datatype ("json" or "xml"), but one uses loadonce: true parameter additionally. In the case the server should return all unfiltered data instead of providing the page of data. The returned data should be still sorted corresponds to sortname, sortorder parameter (which will be sent to the server as sidx and sord). jqGrid displays the first page of returned data, but it fills the internal data parameter with whole rows of data returned from the server. After the first loading of data jqGrid changes datatype to "local" and so the later sorting, paging and filtering of data will be like in case of datatype: "local". In the case yoou will be able to get all the data using grid.jqGrid("getGridParam", "data"), but you can do this of case after the data will be once loaded.