I'm using setCell to set the value of a cell. The problem is it is still calling the customFormatter specified for the column. Is there anyway I can set the value of this cell without it having to go through the customFormatter?
First of all the custom formatter will be used on every grid refresh, so to set the cell value you have to do this after the custom formatter. The best place to do this is inside of loadComplete or gridComplete event handler.
To set the cell value you can use jQuery.text for example. So you should get jQuery object which represent the cell (<td> element) and then use jQuery.text or jQuery.html to change the cell contain. How I understand you, you knows the rowid of the cell and the column name which you want to change. The following code could be:
loadComplete: function() {
var rowid = '2', colName = 'ship_via', tr,
cm = this.p.colModel, iCol = 0, cCol = cm.length;
for (; iCol<cCol; iCol++) {
if (cm[iCol].name === colName) {
// the column found
tr = this.rows.namedItem(rowid);
if (tr) {
// if the row with the rowid there are on the page
$(tr.cells[iCol]).text('Bla Bla');
}
break;
}
}
}
See the corresponding demo here.
Related
I have a grid setup using form editing. I want the the user to be able to edit only some of the rows. As a start, I figured the easiest way to do this was to have a column (probably hidden) in my server query and XML that denotes the Access or Role the user has. So essentially the grid now has a column "Access Role" with 'Y' or 'N' for each row. (where Y = user can edit, N = View/readonly)
I've tried a couple things to implement this. The best I've come up with is using the rowattr function, but my use is flawed since it hides the row in the grid (I don't want it hidden, just readonly):
function (rd) {
console.log('Row = '+rd.WWBPITM_SURROGATE_ID);
if (rd.ACCROLE === "N") {
console.log('RowAttr '+rd.ACCROLE);
return {"style": "display:none"};
}
This might be a start, but I'm not sure where to go from here and I'm not sure if I'm barking up the wrong tree with using rowattr.
I also tried using setCell in a loadComplete function, like this:
function GridComplete() {
var grid = $('#list1');
var rowids = grid.getDataIDs();
var columnModels = grid.getGridParam().colModel;
console.log('Check ACCROLE');
// check each visible row
for (var i = 0; i < rowids.length; i++) {
var rowid = rowids[i];
var data = grid.getRowData(rowid);
console.log('ACCROLE for '+rowid+' is '+data.ACCROLE);
if (data.ACCROLE == 'N') { // view only
// check each column
//console.log(data);
for (var j = 0; j < columnModels.length; j++) {
var model = columnModels[j];
if (model.editable) {
console.log('Is Editable? '+model.editable);
//grid.setCell(rowid, model.name, '', 'not-editable-cell', {editable: false, edithidden: true});
grid.setCell(rowid, model.name, '', 'not-editable-cell', {editoptions: { readonly: 'readonly', disabled: 'disabled' }});
}
}
}
}
}
But the editoptions don't seem to do anything with this.
Any ideas how to do this?
OK thanks for explaining about Form editing. Here's an example of how to prevent edits on certain records for jqGrid with form editing:
Start with this example of jqGrid form edit: http://www.ok-soft-gmbh.com/jqGrid/MulticolumnEdit.htm
Use the beforeInitData event to check your data before the edit form is displayed. Note that this is bound to the pager object.
Use getGridParam and getCell methods to get the current value you want. In my example I grabbed the client name
Add your own business logic for checking (I don't allow edits on 'test2')
Return false to prevent the edit form from popping up.
This example only handles edit, not insert or delete.
Replace $grid.jqGrid("navGrid", "#pager",...) from the example with this:
$grid.jqGrid("navGrid", "#pager", {view: true},
// Events for edit
{
beforeInitData: function (formid) {
var selectedRow = jQuery("#list").jqGrid('getGridParam','selrow'); //get selected rows
var selectedClient = $("#list").jqGrid('getCell', selectedRow, 'name');
if(selectedClient == 'test2')
{
alert('You are not allowed to edit records for client "' + selectedClient + '"');
return false;
}
}
},
// Events for add
{
beforeShowForm: function (formid) {
}
}
);
You didn't provide much information about how you're updating rows (there are various methods as described in JQGrid web page demos, but I took a guess as to a possible solution. I started with the example on the bottom of this page (trirand's web site wiki for inline_editing) http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing and made a few changes.
Added a new data column securityGroup, and put in data like 'A', 'B', 'C'
Displayed the new data column in the grid
The example used the onSelectRow event to start editing a row if you clicked on a new row. I updated this callback to check the value of row['securityGroup'], and only start .editRow if it's in securityGroupA
JSFiddle at http://jsfiddle.net/brianwoelfel/52rrunar/
Here's the callback:
onSelectRow: function(id){
var row = $(this).getLocalRow(id);
if(id && id!==lastsel2){
jQuery('#rowed5').restoreRow(lastsel2);
if(row['securityGroup'] == 'A') {
jQuery('#rowed5').editRow(id,true);
}
lastsel2=id;
}
},
If this method won't work for you, please provide more information about how you're currently doing edits with jqGrid. This example obviously is very trivial and doesn't even post to PHP or mysql or anything.
In case it will be helpful for others, here is how I am implementing Read Only rows in Form Editing mode, based on a column which designates what level of access the user has to each row:
In editoptions, use the beforeShowForm event, like so:
beforeShowForm: function (formid) {
console.log('Checking for READONLY '+formid.name);
var selectedRow = jQuery("#list1").jqGrid('getGridParam','selrow'); //get selected rows
var selRole = $("#list1").jqGrid('getCell', selectedRow, 'ACCROLE');
if(selRole == 'N' || selRole == 'S' || selRole == 'R')
{
//$("<div>Sorry, you do not have access to edit this record.</div>").dialog({title: "Access Denied"});
formid.find("input,select,textarea")
.prop("readonly", "readonly")
.addClass("ui-state-disabled")
.closest(".DataTD")
.prev(".CaptionTD")
.prop("disabled", true)
.addClass("ui-state-disabled");
formid.parent().find('#sData').hide();
var title=$(".ui-jqdialog-title","#edithd"+"list1").html();
title+=' - READONLY VIEW';
$(".ui-jqdialog-title","#edithd"+"list1").html(title);
formid.prepend('<span style="color: Red; font-size: 1em; font-weight: bold;">You viewing READONLY data.</span>');
}
Assume that row numbers is changed from 10 to 30 in navgrid and that we handle onPaging like so:
...
onPaging: function(pgbtn) {
var rowNum = $(this).getGridParam('rowNum');
return 'stop';
}
In jqGrid 4.4.0 rowNum will be 30.
In jqGrid 4.7.0 rowNum will be 10.
Is this expected behaviour because I think rowNum should be 30?
The order of the execution is changed in (compare the line in jqGrid 4.7.0 with the line in jqGrid 4.4.0). jqGrid first changed the rowNum``and then calledonPaging` in jqGrid 4.4.0, but in jqFeid 4.7.0 the oder is changed.
To access to the new value of rowNum one should get the value of rowNum from the corresponding <select> control directly. If you use the pager at the bottom of the grid then the corresponding code could be the following:
onPaging: function (pgButton) {
var p = $(this).jqGrid("getGridParam"),
newRowNum = parseInt($(p.pager).find(".ui-pg-selbox").val());
if (...) { // some stop criteria
return "stop";
}
}
If you use toppager: true option then jqGrid create the pager on the top of the grid and then it change the value of toppager parameter from true to the selector id of the pager. So you can use the code like
onPaging: function (pgButton) {
var p = $(this).jqGrid("getGridParam"),
newRowNum = parseInt($(p.toppager).find(".ui-pg-selbox").val());
if (...) { // some stop criteria
return "stop";
}
}
which just use p.toppager instead of p.pager in the previous code example.
In case of usage both top and bottom pagers you have to get both values and choose the value which is not equal to the value of rowNum parameter:
onPaging: function (pgButton) {
var p = $(this).jqGrid("getGridParam"),
rowNumBottom = parseInt($(p.pager).find(".ui-pg-selbox").val()),
rowNumTop = parseInt($(p.toppager).find(".ui-pg-selbox").val()),
newRowNum = p.rowNum === rowNumTop ? rowNumBottom: rowNumTop;
if (...) { // some stop criteria
return "stop";
}
}
By the way there are exist close problem in case of calling onPaging after other changing in the pager, for example if the user typed new value in the input box with new pager number.
I'm developing now free jqGrid as my fork on github. I change the code of jqGrid so that onPaging receives the second parameter which is object with the properties newPage, currentPage, lastPage, currentRowNum and newRowNum. The corresponding jQuery event jqGridPaging are added too. Moreover I have changed the value of the first parameter so that it corresponds the documentation and the value will be the string "first", "last", "prev" or "next" in case when the user clicked on the corresponding pager button. The version 4.7 used in reality the id of the corresponding pager buttons instead of "first", "last", "prev", "next". So the strings "first", "last", "prev", "next" could be appended with "_" and the id of the pager (or toppager).
Thus one can just use options.newRowNum or options.currentRowNum directly in the code of callback:
onPaging: function (pgButton, options) {
// one can use options.newRowNum directly
// the value options.currentRowNum is identical to
// $(this).jqGrid("getGridParam", "rowNum")
if (...) { // some stop criteria
return "stop";
}
}
In the case of top and bottom pagers, I would add to Oleg's response:
onPaging: function (pgButton) {
var p = $(this).jqGrid("getGridParam"),
rowNumBottom = parseInt($(p.pager).find(".ui-pg-selbox").val()),
rowNumTop = parseInt($(p.toppager).find(".ui-pg-selbox").val()),
newRowNum = p.rowNum === rowNumTop ? rowNumBottom: rowNumTop;
if (...) { // some stop criteria
return "stop";
}
// update the current value so subsequent changes are detected
p.rowNum = newRowNum;
}
This handles the case that the user changes the value on the top pager, then changes it again on the bottom pager. The code above will keep detecting the top pager value.
I am using a custom formatter to create hyperlinks in one of the columns of my grid.
In my code, there are cases when I need to disable the selected row. The row disabling works as I want it to, but the hyperlink for that row is not disabled. I can not select the row and all the other column values are displayed as grey colored to indicate that the row is disabled. The only column whose content does not change color is the one having links.
Any ideas on how to disable links?
This is my loadComplete function:
loadComplete: function (data) {
var ids =jQuery("#list").jqGrid('getDataIDs');
for(var i=0;i < ids.length;i++){
var rowId = ids[i];
var mod = jQuery("#list").jqGrid('getCell',ids[i],'mod');
if(mod=='y'){
jQuery("#jqg_list_"+rowId).attr("disabled", true);
$("#list").jqGrid('setRowData',ids[i],false, {weightfont:'bold',color:'silver'});
var iCol = getColumnIndexByName.call(this, 'adate');
$(this).jqGrid('doInEachRow', function (row, rowId, localRowData) {
$(row.cells[iCol]).children("a").click(function (e) {
e.preventDefault();
// any your code here
alert("No Good");
return false;
});
});
}
}
}
I want the links disabled in all the rows where the value of the column mod=y
You can try to use onClick callback of dynamicLink formatter described here, here and here. It gives you maximum flexibility. Inside of onClick callback you can test something like $(e.target).closest("tr.jqgrow").hasClass("not-editable-row") and just do nothing in the case.
onSelectRow: function (id) {
var row = jQuery('#list').jqGrid('getRowData', lastSel)
...
lastSel = id;
},
Specified in the [Docu]: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods it will not give the actuall value. What can I use instead? The eventually changed data is not submited.
You posted too few code. So it's unknown how you implemented inline editing. In any way you will have the value of the editing cell as the value of the corresponding HTML control. One uses typically <input> or <select> for editing. So to get the value you need find the corresponding HTML element and get directly its value. For example you can use
$("#" + rowid + ">td:nth-child(" + (i + 1) + ")>input").val()
to get the value from the input of the cell from the i-th column or the row having id equal to rowid.
The old answer demonstrate a little other way to do the same. In any way you have to get the value of the corresponding cell directly.
function getTextFromCell(cellNode) {
return cellNode.childNodes[0].nodeName === "INPUT" ?
cellNode.childNodes[0].value :
cellNode.textContent || cellNode.innerText;
}
;
function getActualRowData(rowid) {
var row = [];
$('#' + rowid).find('td').each(function () {
row.push(getTextFromCell(this));
});
return row;
}
Is there a way to add a new row to a slickgrid on demand? For example, have a button on the page that shows the new row when clicked.
It can be done easily using dataView.addItem(params), just replace params with your parameters..
function addNewRow(){
var item = { "id": "new_" + (Math.round(Math.random() * 10000)), "Controller": tempcont, "SrNo1": tempsrno };
dataView.addItem(item);
}
here id, Controller, SrNo1 are ids of colunm
You can add a row dynamically, such as with a button click, by subscribing the "onAddNewRow" listener to your grid object. As many have suggested, it is best to use the dataView plugin to interface with your data. Note that you'll want the "enableAddRow" option set to "true".
Firstly, DataView requires that a unique row "id" be set when adding a new row. The best way to calculate this is by using dataView.getLength() which will give you the number of rows that currently exist in you grid (which we'll use as the id for the new row). The DataView addItem function expects an item object. So we create an empty item object and append the id to it.
Secondly, you'll be only focusing a single cell when you add your data. After you've entered that data (by blurring that cell), DataView will notice that you have not entered data for any of the remaining cells in the row (of course) and will default their values to "undefined". This is not really a desired effect. So what you can do is loop through the columns you've explicitly set and append them to our item object with a value of "" (empty string).
Thirdly, we don't want all the cells to be blank. Actually, we want the original cell's entered data to appear. We have that data so we can set it last so that it will overwrite the "" (empty string) value we previously set.
Lastly, we'll want to update the grid such that it displays all of these changes.
grid.onAddNewRow.subscribe(function (e, args) {
var input = args.item;
var col = Object.keys(input)[0]
var cellVal = input[Object.keys(input)[0]]
// firstly
var item = {};
item.id = dataView.getLength();
// secondly
$.each(columns, function(count, value) {
colName = value.name
console.log(colName)
item[colName] = ""
})
// thirdly
item[col] = cellVal
dataView.addItem(item);
// lastly
grid.invalidateRows(args.rows);
grid.updateRowCount();
grid.render();
grid.resizeCanvas();
});
I hope this helps. Cheers!
You can always add new rows to the grid. All you need to do is add the data object for the row to your grid data.
Assume you create your grid from a data source - myGridData (which is an array of objects).
Just push the new row object to this array. Call the invalidate method on the grid.
Done :)
Beside creating the new row, I needed it to be shown, so that the user can start writing on it. I'm using pagination, so here is what I did:
//get pagination info
var pageInfo = dataView.getPagingInfo();
//add new row
dataView.addItem({id: pageInfo.totalRows});
//got to last page
dataView.setPagingOptions({pageNum: pageInfo.totalPages});
//got to first cell of new row
var aux = totalRows/ pageInfo.pageSize;
var row = Math.round((aux - Math.floor(aux)) * pageInfo.pageSize, 0);
grid.gotoCell(row, 0 ,true);
Before I use pagination, I just needed this:
var newId = dataView.getLength();
dataView.addItem({id: newId});
grid.gotoCell(newId, 0 ,true);
var newRow = {col1: "col1", col2: "col2"};
var rowData = grid.getData();
rowData.splice(0, 0, newRow);
grid.setData(rowData);
grid.render();
grid.scrollRowIntoView(0, false);
Working fine for me.