JqGrid issue on formatter - jqgrid

I'm using this jqgrid:
$("#griglia-navgrid").jqGrid( {
colNames:[...],
colModel:[ {name:'ZMENG_SOR_VRKME_PREC', index:'ZMENG_SOR_VRKME_PREC', width:'5', sortable:false, formatter:numFormat}, ],
...
footerrow:true,
afterInsertRow: function(id){ $("#griglia-navgrid").jqGrid('setCell',id,'ZPARVW_Z1','',{'text-decoration':'underline'}); },
loadComplete: function () {
var $this = $(this),
sum = $this.jqGrid("getCol", "ZMENG_SOR_VRKME", false, "sum"),
$footerRow = $(this.grid.sDiv).find("tr.footrow"),localData = $this.jqGrid("getGridParam", "data"),totalRows = localData.length,totalSum = 0, $newFooterRow, i;
$newFooterRow = $(this.grid.sDiv).find("tr.myfootrow");
if ($newFooterRow.length === 0) {
$newFooterRow = $footerRow.clone();
$newFooterRow.removeClass("footrow").addClass("myfootrow ui-widget-content");
$newFooterRow.children("td").each(function () {
this.style.width = ""; // remove width from inline CSS
});
$newFooterRow.insertAfter($footerRow);
}
for (i = 0; i < totalRows; i++) {
if(localData[i].ZMENG_SOR_VRKME.search("-") == -1){
totalSum += parseFloat(localData[i].ZMENG_SOR_VRKME);}
else{
totalSum -= parseFloat(localData[i].ZMENG_SOR_VRKME);
}
}
$newFooterRow.find(">td[aria-describedby=" + this.id + "_ZPARVW_Z1_NAME]").text("Totale:");
$newFooterRow.find(">td[aria-describedby=" + this.id + "_ZMENG_SOR_VRKME]").text(
$.fmatter.util.NumberFormat(totalSum, $.jgrid.formatter.number.decimalSeparator=',')
);
}
}); //jqGrid
function numFormat( cellvalue, options, rowObject ){
return cellvalue.replace(".",",");
}
It'w works on Safari and Chrome. In firefox i have an error: "ReferenceError: numFormat is not defined".
How can I solve this issue?

The formatter functions should be placed before the JQGrid definition.
THen it would work.

Related

nightwatch assert ALL elements, not ANY

I'm trying to test that, when the Submit button is clicked on an empty form, all the "please fill in this field" labels are displayed.
I'm doing so with this:
page.click('#btn_submit');
page.expect.element('#validation_label_required').to.be.visible;
where #validation_label_required is represented by the CSS selector:
input[required] ~ p.error-message-required
However, this test passes if ANY of the validation labels are visible. The test should only pass if they ALL are.
How can I achieve this?
You will need to create a custom assertion for that where you locate all elements by selenium commands and then loop to verify condition. It should look something like this
var util = require('util');
exports.assertion = function (elementSelector, expectedValue, msg) {
this.message = msg || util.format('Testing if elements located by "%s" are visible', elementSelector);
this.expected = expectedValue;
this.pass = function (value) {
return value === this.expected;
};
this.value = function (result) {
return result;
};
this.command = function (callback) {
var that = this.api;
this.api.elements('css selector',elementSelector, function (elements) {
elements.value.forEach(function(element){
that.elementIdDisplayed(element.ELEMENT,function(result){
if(!result.value){
callback(false);
}
});
});
callback(true);
});
return this;
};
};
I've just ended up with another custom assertion that check how many elements are visible by given css selector.
/**
* Check how many elements are visible by given css selector.
*
*/
var util = require('util');
exports.assertion = function(elementSelector, expectedCount, msg) {
this.message = msg || util.format('Asserting %s elements located by css selector "%s" are visible', expectedCount, elementSelector);
this.expected = expectedCount;
this.count = 0;
this.pass = function(value) {
return value === this.expected;
};
this.value = function(result) {
return this.count;
};
this.command = function(callback) {
var me = this, elcount = 0;
this.count = 0;
this.api.elements('css selector', elementSelector, function(elements) {
if(elements.value && elements.value.length > 0){
elcount = elements.value.length;
}else{
return callback(false);
}
elements.value.forEach(function(element) {
me.api.elementIdDisplayed(element.ELEMENT, function(result) {
if (result.value) {
me.count++;
}
elcount--;
if (elcount === 0) {
callback(me.count);
}
});
});
});
};
};

onpropertychange does not trigger when type the first word in IE8

if give a value to input when bind propertychange event,it will not trigger the first change
window.onload=function(){
var textBox = document.createElement("input");
document.body.appendChild(textBox);
textBox.value='qw';
//赋值后立即绑定,IE8输入第一个字符的时候不会触发onpropertychange
textBox.attachEvent('onpropertychange',function(){
alert(textBox.value);
});
};
e.g.
type "12345"
there's nothing happened when type "1";
how to fixit without setTimeout;
i add keyup event to fix IE8
if (browser.ie < 10) {
// 检查是否为可输入元素
var isInput = function(elem) {
return elem.nodeName == 'INPUT' || elem.nodeName == 'TEXTAREA';
},
iefx = _.uniqueId('.ieinputFixed');
$.event.special.input = {
setup: function() {
if (!isInput(this)) return false;
var elem = this,
oldValue = this.value,
setter = function() {
if (oldValue !== elem.value) {
oldValue = elem.value;
$.event.trigger('input', null, elem);
}
},
doc = $(document);
// oldValue = elem.value;
if (browser.ie == 9 || browser.ie == 8) {
$(elem).on('focus' + iefx, function() {
doc.on('selectionchange' + iefx, setter);
}).on('blur' + iefx, function() {
doc.off('selectionchange' + iefx, setter);
});
}
// IE8
if (browser.ie == 8) {
$(elem).on('keyup' + iefx, setter);
}
//ie6-9
elem.attachEvent('onpropertychange', $.data(elem, iefx, function(event) {
if (event.propertyName.toLowerCase() == "value") {
setter();
}
}));
},
teardown: function() {
if (!isInput(this)) return false;
if (browser.ie == 9 || browser.ie == 8) $.event.remove(this, iefx);
this.detachEvent('onpropertychange', $.data(this, iefx));
$.removeData(this, iefx);
}
};
}

SlickGrid filter not working

I am fairly new to SlickGrid. I am trying to make SlickGrid filter work but no luck. I am following the example (http://mleibman.github.io/SlickGrid/examples/example4-model.html).
Below is my source code.
$(document).ready(function() {
var tName;
$('#submit').click(function(e) {
tName = $('#source option:selected').text();// name1
tName = tName.trim();
$.ajax({
url : 'someUrl',
type : 'GET',
cache : false,
success : function(d) {
var grid;
var searchString = "";
var data = [];
var columns = new Array();
var cols = d[0].columns;
var pkColNames = d[0].pkColNames;
for (var j=0; j< cols.length; j++) {
var key = {id: cols[j].colName, name: cols[j].colName, field: cols[j].colName, width: 200, sortable:true, editor: Slick.Editors.LongText};
columns[j] = key;
}
var options = {
editable: true,
enableAddRow: false,
enableCellNavigation: true,
asyncEditorLoading: false,
enableColumnReorder:true,
multiColumnSort: false,
autoEdit: false,
autoHeight: false
};
function myFilter(item, args) {
return true;// Let us return true all time ?
}
for (var i = 0; i < d.length; i++) {
var tempData = (data[i] = {});
var title = null;
var val = null;
for (var q = 0; q < d[i].columns.length; q++) {
title = d[i].columns[q].colName;
val = d[i].columns[q].colValue;
tempData[title] = val;
}
}
var dataView = new Slick.Data.DataView({ inlineFilters: true });
grid = new Slick.Grid("#myGrid", dataView, columns, options);
dataView.setPagingOptions({
pageSize: 25
});
var pager = new Slick.Controls.Pager(dataView, grid, $("#myPager"));
var columnpicker = new Slick.Controls.ColumnPicker(columns, grid, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
grid.onAddNewRow.subscribe(function(e, args) {
// Adding a new record is not yet decided.
});
grid.onCellChange.subscribe(function (e) {
var editedCellNo = arguments[1].cell;
var editedColName = grid.getColumns()[editedCellNo].field;
var newUpdatedValue= arguments[1].item[grid.getColumns()[editedCellNo].field];
var editedColType = "";
for (var cnt = 0; cnt < cols.length; cnt++) {
if (editedColName == cols[cnt].colName) {
editedColType = cols[cnt].colType;
break;
}
}
var pkKeyValue="";
for (var v=0; v <pkColNames.length;v++) {
for (var p=0; p<grid.getColumns().length; p++) {
if (pkColNames[v] == grid.getColumns()[p].field) {
var value = arguments[1].item[grid.getColumns()[p].field];
pkKeyValue += "{"+pkColNames[v] + '~' +getColDbType(grid.getColumns()[p].field) + ":"+value+"},";
break;
}
}
}
function getColDbType(colName) {
for (var c = 0; c < cols.length; c++) {
if (colName == cols[c].colName) {
return cols[c].colType;
}
}
}
pkKeyValue = pkKeyValue.substring(0, pkKeyValue.length-1);
$.ajax({
url: 'anotherUrl',
type:'GET',
dataType:'text',
success: function(f) {
bootbox.alert("Data updated successfully");
},
error: function() {
bootbox.alert("Error - updating data. Please ensure you are adding the data in right format.");
grid.invalidateAllRows();
grid.render();
}
});
});
grid.onClick.subscribe(function (e) {
//do-nothing
});
dataView.onRowsChanged.subscribe(function(e, args) {
grid.updateRowCount();
grid.invalidateRows(args.rows);
grid.render();
});
grid.onSort.subscribe(function(e, args) {
// args.multiColumnSort indicates whether or not this is a multi-column sort.
// If it is, args.sortCols will have an array of {sortCol:..., sortAsc:...} objects.
// If not, the sort column and direction will be in args.sortCol & args.sortAsc.
// We'll use a simple comparer function here.
var comparer = function(a, b) {
return a[args.sortCol.field] > b[args.sortCol.field];
}
// Delegate the sorting to DataView.
// This will fire the change events and update the grid.
dataView.sort(comparer, args.sortAsc);
});
// wire up the search textbox to apply the filter to the model
$("#txtSearch").keyup(function (e) {
console.log('Called...txtSearch');
Slick.GlobalEditorLock.cancelCurrentEdit();
// clear on Esc
if (e.which == 27) {
this.value = "";
}
searchString = this.value;
updateFilter();
});
function updateFilter() {
console.log("updateFilter");
dataView.setFilterArgs({
searchString: searchString
});
dataView.refresh();
}
dataView.beginUpdate();
dataView.setItems(data, pkColNames);
dataView.setFilterArgs({
searchString: searchString
});
dataView.setFilter(myFilter);
dataView.endUpdate();
},
error : function() {
bootbox.alert("Invalid user");
}
});
});
});
Your function myFilter() is always returning true so of course it will never work. The example that you looked at, was to filter something specific. I would recommend that you look at the following example to have a generic filter. From the example, simply type the text you are looking on a chosen column and look at the result... see example below (from SlickGrid examples).Using fixed header row for quick filters
In case you want a more in depth conditional filters ( > 10, <> 10, etc...), please take a look at my previous answer on how to make this kind of filtering possible, see my previous answer below:SlickGrid column type
Hope that helps you out

Sorting array declared in Kendoui Observable

I have declared an content array in my kendoui observable but how do i sort it in the add function. Here's my code.
var cart = kendo.observable({
contents: [],
cleared: false,
contentsCount: function () {
return this.get("contents").length;
},
isEmpty: function () {
return (this.get("contents").length == 0);
},
add: function (item) {
var found = false;
this.set("cleared", false);
for (var i = 0; i < this.contents.length; i++) {
var current = this.contents[i];
if (current.item.id == item.id) {
current.set("quantity", current.get("quantity") + 1);
found = true;
break;
}
}
if (!found) {
this.contents.push({ item: item, quantity: 1 });
}
// I NEED TO SORT THE ARRAY HERE.
},
});

how to persist current row in jqgrid

How to presist current row if grid is opened again or page is refreshed ?
Answer in Persisting jqGrid column preferences describes how to persist column width and some other parameters.
In this answer demo I clicked in some row and pressed F5 . Previous clicked row was not highlighted.
How to save / restore current row in local storage ?
Update
If jqGrid column structure is modified in application and user opens application from browser again,
restorecolumnstate creates invalid colmodel where some elements are missing. This causes exception in refreshSearchingToolbar which assumes that all colmodel elements are present.
How to fix this ? How to dedect modified colmodol and not to restore colmodel in this case ? Or should restoreColumnState update colModel so that proper array is created ?
**Update 2 **
If myColumnsState.permutation contains nulls $grid.jqGrid("remapColumns", myColumnsState.permutation, true) created invalid colmodel. Here are screenshots from VS debugger immediately before and after remapColumns call
after:
I fixed this by chaning code to
if (isColState && myColumnsState.permutation.length > 0) {
var i, isnull = false;
for (i = 0; i < myColumnsState.permutation.length; i = i + 1) {
if (myColumnsState.permutation[i] == null) {
isnull = true;
break;
}
}
if (!isnull) {
$grid.jqGrid("remapColumns", myColumnsState.permutation, true);
}
Is this best solution ?
I combined the code from the previous answer about persisting jqGrid column preferences with the code of from another answer where I suggested the code which implemented persistent selection of rows. It's important to mention, that in case of multiselect:true it will be used the array of ids of selected rows which contains all selected even if the rows are on another page. It's very practical and the implementation very simple. So I posted the corresponding feature request, but it's stay till now unanswered.
Now I can present two demos: the first demo which use multiselect: true and the second demo which uses the same code, but with the single selection.
The most important parts of the code which I used you will find below.
One thing is very important to mention: you should modify the value of myColumnStateName in every page which you use. The value of the variable contain the name of the column state in the localStorage. So it you would not change the name you will share state of different tables which can follows to very strange effects. You can consider to use names constructed from the name of the current page or it's URL as the value of myColumnStateName.
var $grid = $("#list"),
getColumnIndex = function (grid, columnIndex) {
var cm = grid.jqGrid('getGridParam', 'colModel'), i, l = cm.length;
for (i = 0; i < l; i++) {
if ((cm[i].index || cm[i].name) === columnIndex) {
return i; // return the colModel index
}
}
return -1;
},
refreshSerchingToolbar = function ($grid, myDefaultSearch) {
var postData = $grid.jqGrid('getGridParam', 'postData'), filters, i, l,
rules, rule, iCol, cm = $grid.jqGrid('getGridParam', 'colModel'),
cmi, control, tagName;
for (i = 0, l = cm.length; i < l; i++) {
control = $("#gs_" + $.jgrid.jqID(cm[i].name));
if (control.length > 0) {
tagName = control[0].tagName.toUpperCase();
if (tagName === "SELECT") { // && cmi.stype === "select"
control.find("option[value='']")
.attr('selected', 'selected');
} else if (tagName === "INPUT") {
control.val('');
}
}
}
if (typeof (postData.filters) === "string" &&
typeof ($grid[0].ftoolbar) === "boolean" && $grid[0].ftoolbar) {
filters = $.parseJSON(postData.filters);
if (filters && filters.groupOp === "AND" && typeof (filters.groups) === "undefined") {
// only in case of advance searching without grouping we import filters in the
// searching toolbar
rules = filters.rules;
for (i = 0, l = rules.length; i < l; i++) {
rule = rules[i];
iCol = getColumnIndex($grid, rule.field);
if (iCol >= 0) {
cmi = cm[iCol];
control = $("#gs_" + $.jgrid.jqID(cmi.name));
if (control.length > 0 &&
(((typeof (cmi.searchoptions) === "undefined" ||
typeof (cmi.searchoptions.sopt) === "undefined")
&& rule.op === myDefaultSearch) ||
(typeof (cmi.searchoptions) === "object" &&
$.isArray(cmi.searchoptions.sopt) &&
cmi.searchoptions.sopt.length > 0 &&
cmi.searchoptions.sopt[0] === rule.op))) {
tagName = control[0].tagName.toUpperCase();
if (tagName === "SELECT") { // && cmi.stype === "select"
control.find("option[value='" + $.jgrid.jqID(rule.data) + "']")
.attr('selected', 'selected');
} else if (tagName === "INPUT") {
control.val(rule.data);
}
}
}
}
}
}
},
saveObjectInLocalStorage = function (storageItemName, object) {
if (typeof window.localStorage !== 'undefined') {
window.localStorage.setItem(storageItemName, JSON.stringify(object));
}
},
removeObjectFromLocalStorage = function (storageItemName) {
if (typeof window.localStorage !== 'undefined') {
window.localStorage.removeItem(storageItemName);
}
},
getObjectFromLocalStorage = function (storageItemName) {
if (typeof window.localStorage !== 'undefined') {
return JSON.parse(window.localStorage.getItem(storageItemName));
}
},
myColumnStateName = 'ColumnChooserAndLocalStorage2.colState',
idsOfSelectedRows = [],
saveColumnState = function (perm) {
var colModel = this.jqGrid('getGridParam', 'colModel'), i, l = colModel.length, colItem, cmName,
postData = this.jqGrid('getGridParam', 'postData'),
columnsState = {
search: this.jqGrid('getGridParam', 'search'),
page: this.jqGrid('getGridParam', 'page'),
sortname: this.jqGrid('getGridParam', 'sortname'),
sortorder: this.jqGrid('getGridParam', 'sortorder'),
permutation: perm,
selectedRows: idsOfSelectedRows,
colStates: {}
},
colStates = columnsState.colStates;
if (typeof (postData.filters) !== 'undefined') {
columnsState.filters = postData.filters;
}
for (i = 0; i < l; i++) {
colItem = colModel[i];
cmName = colItem.name;
if (cmName !== 'rn' && cmName !== 'cb' && cmName !== 'subgrid') {
colStates[cmName] = {
width: colItem.width,
hidden: colItem.hidden
};
}
}
saveObjectInLocalStorage(myColumnStateName, columnsState);
},
myColumnsState,
isColState,
restoreColumnState = function (colModel) {
var colItem, i, l = colModel.length, colStates, cmName,
columnsState = getObjectFromLocalStorage(myColumnStateName);
if (columnsState) {
colStates = columnsState.colStates;
for (i = 0; i < l; i++) {
colItem = colModel[i];
cmName = colItem.name;
if (cmName !== 'rn' && cmName !== 'cb' && cmName !== 'subgrid') {
colModel[i] = $.extend(true, {}, colModel[i], colStates[cmName]);
}
}
}
return columnsState;
},
updateIdsOfSelectedRows = function (id, isSelected) {
var index = idsOfSelectedRows.indexOf(id);
if (!isSelected && index >= 0) {
idsOfSelectedRows.splice(index, 1); // remove id from the list
} else if (index < 0) {
idsOfSelectedRows.push(id);
}
},
firstLoad = true;
myColumnsState = restoreColumnState(cm);
isColState = typeof (myColumnsState) !== 'undefined' && myColumnsState !== null;
idsOfSelectedRows = isColState && typeof (myColumnsState.selectedRows) !== "undefined" ? myColumnsState.selectedRows : [];
$grid.jqGrid({
// ... some options
page: isColState ? myColumnsState.page : 1,
search: isColState ? myColumnsState.search : false,
postData: isColState ? { filters: myColumnsState.filters } : {},
sortname: isColState ? myColumnsState.sortname : 'invdate',
sortorder: isColState ? myColumnsState.sortorder : 'desc',
onSelectRow: function (id, isSelected) {
updateIdsOfSelectedRows(id, isSelected);
saveColumnState.call($grid, $grid[0].p.remapColumns);
},
onSelectAll: function (aRowids, isSelected) {
var i, count, id;
for (i = 0, count = aRowids.length; i < count; i++) {
id = aRowids[i];
updateIdsOfSelectedRows(id, isSelected);
}
saveColumnState.call($grid, $grid[0].p.remapColumns);
},
loadComplete: function () {
var $this = $(this), i, count;
if (firstLoad) {
firstLoad = false;
if (isColState) {
$this.jqGrid("remapColumns", myColumnsState.permutation, true);
}
if (typeof (this.ftoolbar) !== "boolean" || !this.ftoolbar) {
// create toolbar if needed
$this.jqGrid('filterToolbar',
{stringResult: true, searchOnEnter: true, defaultSearch: myDefaultSearch});
}
}
refreshSerchingToolbar($this, myDefaultSearch);
for (i = 0, count = idsOfSelectedRows.length; i < count; i++) {
$this.jqGrid('setSelection', idsOfSelectedRows[i], false);
}
saveColumnState.call($this, this.p.remapColumns);
},
resizeStop: function () {
saveColumnState.call($grid, $grid[0].p.remapColumns);
}
});
$grid.jqGrid('navGrid', '#pager', {edit: false, add: false, del: false});
$grid.jqGrid('navButtonAdd', '#pager', {
caption: "",
buttonicon: "ui-icon-closethick",
title: "clear saved grid's settings",
onClickButton: function () {
removeObjectFromLocalStorage(myColumnStateName);
window.location.reload();
}
});
UPDATED: I forgot to mention that in case of usage multiselect: true option with jqGrid 4.3 it is very important to use the fix which described here. In the first demo I used the modified version of the jquery.jqGrid.src.js which include the bug fix.
UPDATED 2: To make easy to generate unique name of the local storage item used to save the grid state I modified the demos a little. The next version of the multiselect demo and the single select demo use myColumnStateName as the function defined as the following
var myColumnStateName = function (grid) {
return window.location.pathname + '#' + grid[0].id;
}
The usage of myColumnStateName are changed correspondingly. Additionally I extended the column state to save the rowNum value.
UPDATED 3: The answer describe how one can use new possibility of free jqGrid to save the grid state.
Oleg's solution generates an error when you refresh the page like below.
Error: Uncaught TypeError: Cannot read property 'el' of undefined
Line: 1936 in jquery.jqGrid.src.js
var previousSelectedTh = ts.grid.headers[ts.p.lastsort].el, newSelectedTh = ts.grid.headers[idxcol].el;
Solution to this is to save the lastsort grid parameter and reset it when load complete like below.
saveColumnState = function(perm) {
...
columnsState = {
search: this.jqGrid('getGridParam', 'search'),
page: this.jqGrid('getGridParam', 'page'),
sortname: this.jqGrid('getGridParam', 'sortname'),
sortorder: this.jqGrid('getGridParam', 'sortorder'),
lastsort: this.jqGrid('getGridParam', 'lastsort'),
permutation: perm,
colStates: { }
},
...
},
loadComplete: function(data) {
...
if (isColState) {
$this.jqGrid("remapColumns", myColumnsState.permutation, true);
if(myColumnsState.lastsort > -1)
$this.jqGrid("setGridParam", { lastsort: myColumnsState.lastsort });
}
...
},

Resources