Slickgrid add new row on demand - slickgrid

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.

Related

Retaining Grid Row selection in kendo ui

I am using Kendo UI grid without pagination. I have set the below code to load the data in the grid view while scrolling
scrollable: { virtual: true },
My problem is, I have selected 100th row in the grid by scrolling . I am refreshing the grid. After refresh, I need to select the 100th row again. Is it possible ?
Regards
Senthil
After refresh select the row you need as shown below
var grid = $("#grid").data("kendoGrid");
grid.select("tr:eq(100)");
For more info check out kendo DOC http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#methods-select
Basically the question is annotate the row that you have selected when it changes to do so and then in dataBound event select that same row.
In order to save the selected row you can do:
change: function (e) {
// Save some information from the selected row
var item = this.dataItem(this.select());
// Here we save uid
var uid = item.uid;
this.selectedRow = uid;
},
dataBound: function (e) {
// If we have any row selected
if (this.selectedRow) {
// Use this.select for selecting it
this.select("tr[data-uid='" + this.selectedRow + "']");
}
}
You can see this here: http://jsfiddle.net/OnaBai/eLk7zkzs/

Kendo - Grid - Remove Multiple Rows

I have the following code that remove rows that are checked (each row has a checkbox and I have a Filter button (and other buttons) in the toolbar).
var grid = $("#resultsGrid").data("kendoGrid");
grid.tbody.find("input:checked").closest("tr").each( function(index) {
grid.removeRow($(this));
});
However, performance starts to become an issue when there are > 20 rows being removed. However, kendo filters (removes) 20 rows or more much faster. How is kendo filtering removing multiple rows from the view? Or is there some other better way to remove multiple rows from the grid? Thanks in advance for your help.
** Updated Fiddle to new location - Same code as before **
Try dealing with the data directly. Have the checkbox hooked to the row's Id and filter on that.
I linked a fiddle that removes array elements and then re-creates the grid. The 2 text boxes at the top of the grid capture the range of Ids that you want to remove (this would be the same array of your checkboxIds). Then I cycled through those "remove Ids", removed them from the data array and remade the grid.
I slightly modified a previous fiddle and that's why I'm re-creating the grid instead of dealing with the DataSource object directly. But I hope you get the gist of what I'm doing.
I have 1000 records in this example (only 3 columns) but it removes 950 records very quickly.
Fiddle- Remove from data array
Let me know if you need an example of this with the KendoUI DataSource object.
I included this code below because StackOverflow wouldn't let me post without it.
function filterData() {
var val1 = $("#val1").val();
var val2 = $("#val2").val();
var removeIndexes = new Array();
for (var i = val1; i <= val2; i++) {
removeIndexes.push(i);
}
$(removeIndexes).each(function(removeIndex) {
var removeItemId = this;
$(randomData).each(function(dataIndex) {
var continueLoop = true;
if (this.Id == removeItemId) {
randomData.splice(dataIndex, 1);
continueLoop = false;
}
return continueLoop;
});
});
createGrid();
}
You should use batch updates:
$("#resultsGrid").kendoGrid({
dataSource: {
batch: true,
...
}, ...});
var grid = $("#resultsGrid").data("kendoGrid");
grid.tbody.find("input:checked").closest("tr").each( function() {
var dataItem = grid.dataItem(this);
grid.dataSource.remove(dataItem);
});
grid.dataSource.sync(); // this applies batched changes

Disable specific rows in a SlickGrid table

This is how my table looks:
a checkBox column
a name column
The table contains 5 rows.
What I want to achieve is to make the last two rows of the table unselectable (the respective checkboxes in the checkBox column should also disappear).
I managed to do this with jQuery after the table was rendered. Does the SlickGrid table allow me to perform the above mentioned scenario?
You can add a function for returning getItemMetadata() which is demonstrated in this example.
Here's a simplified version:
function getItemMetaData(row){
if (row >= view.getLength() - 2){ //only on last two rows.
return { selectable: false };
} else {
return {};
}
}
var view = new Slick.Data.DataView();
view.getItemMetadata = getItemMetaData;
var grid = new Slick.Grid(selector, view, cols, opts);
This method is then called in canCellBeSelected at line 2944 in slick.grid.js

How to append new records to existing records in a jqGrid?

I am populating Grid2 from the records selected from Grid1. however The records added are getting replaced by the new set of records from Grid1 whenever i select and add again. below is my code. This is only for the UI. I thought of appending the new records as below. Please guide with the correct code
function StuffData(data) {
var g = jQuery('#Grid2');
var usersList = data;
var totalRecords= jQuery('#Grid2').jqGrid('getGridParam','records');
alert('Grid records' +totalRecords);
if (usersList!=null) {
g.jqGrid('clearGridData',false);
for(var i=0;i<=usersList.length;i++){
// g.jqGrid('addRowData',i+1,usersList[i]);
g.jqGrid('addRowData',totalRecords+1,usersList[i]);
totalRecords += 1;
// g.jqGrid('addRowData',0,usersList);
}
}
}
The call to clearGridData is removing the old rows from the grid. From the jqGrid documentation:
clearGridData
Clears the currently loaded data from grid. If the clearfooter parameter is set to true, the method clears the data placed on the footer row.
If you only want to append data, you should be able to just remove this line of code. Or am I missing something?

JQGrid setCell customFormatter

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.

Resources