Kendo Grid: Keep custom popup open after save new record - kendo-ui

I've got a custom popup editor template for my Kendo Grid which contains tabs. One of the tabs is to have a second Kendo Grid of records relating to the record being edited.
I'd like to be able to create a new record and immediately start adding the related records, without having to re-open the newly created record. Obviously, I have to first save the record in order for its ID to be generated.
I've managed to prevent the popup editor closing when new records are saved, but I think the popup window is no longer bound to the model at this point.
Is there a way I can rebind the window to the model so I can carry on editing and adding the related records?
Thanks
Edit: Here's the technique for keeping the editor open:
The grid's edit and save events:
edit: function(e){
var editWindow = this.editable.element.data("kendoWindow");
editWindow.bind("close", onWindowEditClose);
},
save: function(e){
if (e.model.isNew()) {
preventCloseOnSave = true;
} else {
preventCloseOnSave = false;
}
}
The onWindowEditClose:
var onWindowEditClose = function(e) {'
if (preventCloseOnSave) {
e.preventDefault();
preventCloseOnSave = false;
}
};

I ended up using a slightly clunky workaround, but other than a minor UI 'flash' it works okay.
The Grid has a rowTemplate, so I've added the record's ID field to the TR tags so I can find them by ID. I then have a function that runs on the complete event when a new record is created which finds the new row and immediately opens it:
var ds = new kendo.data.DataSource({
// ...
transport: {
create: {
url: '/url/to/create',
dataType: 'json',
type: 'post',
complete: recordCreated
}
});
function recordCreated(e) {
"use strict";
var id = e.responseJSON.data[0].id,
grid = $('#grid').data("kendoGrid"),
row = grid.tbody.find("tr[data-id='" + id + "']");
grid.editRow(row);
}

On a conceptual level, you could intercept the POST action that saves the record to the database and get the saved data on return. Note that your POST action must return the saved object (as is expected). You can hook into this event by using the requestEnd method of the Kendo UI Datasource object that supports your grid and bind the saved record to your edit window (as long as you have a reference to it).
var ds = new kendo.data.DataSource({
// ...
requestEnd: function (e) {
kendo.bind(editWindow, e.response); // bind the returned data to your edit window
}
});

The understanding of the kendo ui structure (which can be tedious at times) is important to getting anything done with it. The closing of the popup that allows inserting is done in the dataBinding event. Therefore, that is the place we need to prevent it from:
$("#yourgrid").kendoGrid({
dataSource: yourDataSource,
columns: [
{ field: "YouColumn", title: "YourTitle", ... },
...
]
.
.
.
editable: "popup",
dataBinding: function(e){
//this is the key to keeping the popup open
e.preventDefault();
},
save: function (e) {
//whatever you need to do here
}
.
.
.
});
Hope this helps someone.
//Houdini

Related

kendo-datasource autoSync causes navigation placeholder to return to upper left corner of the grid

I'm using kendo-ui with angularJS 1.5 and I have a simple kendo-grid bound to a datasource with transport configured using functions as follows:
private buildDataSource() {
this.dataSource = new kendo.data.DataSource({
autoSync: true,
change: this.dataSourceChangeHandler.bind(this),
error: this.dataSourceErrorHandler.bind(this),
transport: {
read: this.dataSourceRead.bind(this),
create: this.dataSourceCreate.bind(this),
update: this.dataSourceUpdate.bind(this),
destroy: this.dataSourceDestroy.bind(this)
},
[...]
});
}
private dataSourceUpdate(e: kendo.data.DataSourceTransportUpdate) {
var updatedItem: KendoCosto = e.data;
[...]
e.success(updatedItem, undefined, undefined);
}
The grid options looks like this:
this.gridOptions = {
dataSource: this.dataSource,
change: this.gridChangeHandler.bind(this),
editable: {
mode: "incell",
confirmation: false
},
navigatable: true,
selectable: "multiple, cell",
allowCopy: true,
toolbar: [
"create"
],
[...]
The grid works fine and the read, create, update, destroy behave as expected.
My problem is that whenever I change a value in a grid's cell and hit enter, I would like to have keyboard navigation "placeholder" (the grid has navigatable: true) to remain on the edited cell, but it happens to be moved to the upper left corner cell.
This behavior happens only when dataSource's autoSync is set to true.
I've also tried to "set" the current cell via the ".current" method of the grid's api but it doesn't seem to work:
// this is bound to the grid's change event and it is supposed to
// store the currently selected cell in a property of the class
// that builds both the datasource and the grid
private gridChangeHandler(e: kendo.ui.GridNavigateEvent)
{
this.thisGrid = this.thisGrid || e.sender;
this.currentCell = e.sender.current();
}
// Then on the change event of the datasource I do
private dataSourceChangeHandler(event: kendo.data.DataSourceChangeEvent)
{
if (this.currentCell && this.thisGrid) {
this.thisGrid.select(this.currentCell);
this.currentCell = undefined;
}
}
any suggestions ?
Thanks in advance !
--- edit ---
The code I posted/pasted in the comment is absolutely unreadable so I'm repeating the code here:
To have your solution work, I had to modify my dataBound handler this way.
private gridDataBoundHandler(e: kendo.ui.GridDataBoundEvent) {
if (this.thisGrid && this.currentCell) {
setTimeout((() => {
// this.thisGrid.editCell(this.currentCell);
this.thisGrid.current(this.currentCell);
}).bind(this)
, 10);
}
}
without the timeout, the navigation placeholde was still resetting back to the upper left corner.
First, I think the grid change event is the wrong event to attach to as it only fires when the user selects a row/cell with the mouse...it will not fire on tab events.
So, I would use the grid save event, which fires after you make an edit and "commit" the change through enter, tab, mouse off, etc.
Second, the e.sender.current() includes the current identifying information like "grid_active_cell" and "k-state-focused" and "k-dirty-cell", etc. By the time you get to the dataSource change event, the cell has actually lost all that decoration and your this.currentCell is essentially pointing at a non-existent selector. So, you need to grab a more "permanent" identifier.
So, using the grid save event:
save: function (e) {
var row = $(e.sender.current()).closest("tr");
var colIdx = $("td", row).index(e.sender.current());
var model = e.sender.dataItem(row);
currentCell = "tr[data-uid='" + model.uid + "'] td:eq(" + colIdx + ")";
}
And then in the grid DATABOUND event(as the dataSource change event is still followed by events that change the cell focus to the top-left, but grid.dataBound is further in the chain and seems to work better):
dataBound: function (e) {
if (currentCell) {
grid.editCell(currentCell);
grid.current(currentCell);
}
}
Demo(with variable changes as I do not have your whole class, based on a kendo grid demo): http://dojo.telerik.com/#Stephen/OjAsU
Note that this solution(not my implementation, but your technique in general) will break tabbing from cell to cell, i.e. tabbing will commit the edit but the dataSource change event will always put the focus back on the just-edited cell instead of moving to the tabbed-to cell. This breaks user expectation of what tab does. So, you should consider trying to capture the enter key press only instead of relying on the grid events(which fire regardless of tab or enter).

Kendo UI: Excel Export not working correctly after datasource refreshing data

I have a Grid, when users click a button, it gets some parameters and refresh datasource:
var grdUP = $("#weblogGrid").data("kendoGrid");
grdUP.dataSource.transport.options.read.url = url; // new url
//Read data source to update
grdUP.dataSource.read();
it works fine. the new data shows in the grid. And the grid has another button, which will export the data to excel. I'm using below code (also tried the built-in button):
var grid = $("#weblogGrid").data("kendoGrid");
grid.saveAsExcel();
it actually exports the data to excel file.
However, it always exports the initial data in the grid, not the data user refreshed.
For example, when the grid first shows up, it has 10 rows data. After refresh, it has 5 rows data. Now, if export, it still exports 10 rows data although the data in grid is different.
Is this a Bug? or, maybe I did something wrong in refresh grid?
Thanks
===============================
edit to clarify something
Thanks. currently, I got new data using:
var url = '/WeblogReport/GetWebLogList?fromDate=' + fromDate + '&toDate=' + toDate;
var grdUP = $("#myGrid").data("kendoGrid");
//Set url property of the grid data source
grdUP.dataSource.transport.options.read.url = url;
//Read data source to update
grdUP.dataSource.read();
So I changed to:
// get value of date
....
$.ajax({
type: "GET",
dataType: "json",
url: "/WeblogReport/GetWebLogList",
data: { FromDate: fromDate, ToDate: toDate },
success: function (data) {
alert(data);
var grid = $("#myGrid").data("kendoGrid");
grid.dataSource.data(data);
grid.refresh();
}
});
Somehow, it does not show the new data. Any suggestions?
Thank you very much.
add more clarification
Here is in the Json call.
success: function (data) {
var newdata = [{ "UserName": "username", "ClientIP": "1.1.1.1"}];
$("#myGrid").data("kendoGrid").dataSource.data(newdata);
$("#myGrid").data("kendoGrid").refresh();
//$("#myGrid").data("kendoGrid").saveAsExcel();
}
Set both of the following fields to make Excel export work:
grid.dataSource.transport.options.read.url = url;
grid.options.dataSource.transport.read.url = url;
check this:
http://jsfiddle.net/Sowjanya51/o8cw3vj8/
$('#grid1').data('kendoGrid').dataSource.data(newdata);
$('#grid1').data('kendoGrid').refresh();
You need to update the dataSource and reload the grid,otherwise the grid dataSource will still have reference to old data even though UI displays the new data.
Just set the "allPages" option on your grid to "True". like so :
excel: {
fileName: "Export.xlsx",
filterable: true,
allPages: true
},
Your original solution should be fine if you refresh the grid after you read from the data source.
var grdUP = $("#weblogGrid").data("kendoGrid");
grdUP.dataSource.transport.options.read.url = url; // new url
//Read data source to update
grdUP.dataSource.read();
//add this line to refresh the active data set in the grid
grdUP.refresh();
I had run into the same issue and this solved it for me. The only difference between your approach and mine is that you're changing the data source's read URL, whereas I was changing the data parameters for the read method. Shouldn't make any difference, but I'll mention that just in case.

kendo ui form update cancel button

I am trying to a simple kendo ui form with 'Save' and 'Cancel' buttons. I am using the Kendo.Observable to bind the data to the form.
The functionality I am trying to achieve is, if the 'Save' button is clicked, the form data will be saved. Else, if 'Cancel' is clicked the form will come back to read-only mode with the previous data that was present. To do this, I am first saving the model data in a 'originalvalue' property on click of Update button. If 'Cancel' is clicked, the 'fields' model data is restored to the 'originalvalue'. But the issue is that the , 'originalvalue' does not contain the original value. It gets updated when the user is editing during 'Save'.
The question is - how do I retain the original model data so that it can be refreshed on cancel?
Please find below the code. Appreciate your help, thanks.
<script type="text/javascript">
var viewModel = kendo.observable ({
updated: false,
originalvalue: {},
update: function(e) {
var original = this.get("fields");
this.set("originalvalue", original);
this.set("updated", true);
},
save: function(e) {
e.preventDefault();
if (validator.validate()) {
// make an ajax call to save this data
this.set("updated", false);
}
},
cancel: function(e) {
var original = this.get("originalvalue");
validator.destroy();
this.set("fields", original);
this.set("updated", false);
},
fields: {}
});
viewModel.set("fields", formArray);
kendo.bind($("#outerForm"), viewModel);
// prepare the validator
var validator = $("#outerForm").kendoValidator().data("kendoValidator");
I had to make the exact thing on a form I am currently developing. I am using a DataSource object for the data so I had to use cancelChange().
The thing I did there:
1. I made a Datasource with a schema:
... schema: {
model: {id: "id"}}
...
2. I got the object I was editing with the mapped id:
clientDataSource.cancelChanges(clientDataSource.get(this.get("contactID")));
where the ContactID is created in a setData function where I have passed the ID:
this.set("contactID", contactID);
As I may have notices and understood, you have another problem here where you arent using a DataSource but rather data for fields?
The problem here is that your originalValue is inside the Observable object and it is referenced to the variable original and thus it has observable properties. You should have the variable originalValue defined outside the observable object:
var originalValue;
var viewModel = kendo.observable ({ ...
And you should send the formArray also to that variable so you will have the defaults load before even the observable object is loaded such as:
originalValue = formArray;
viewModel.set("fields", formArray);
So when you need to cancel it you should have:
cancel: function(e) {
var original = originalValue;
validator.destroy();
this.set("fields", original);
this.set("updated", false);
},
I havent tested it but it should provide you some guidance on how to solve that problem.

How to change columns set of kendo grid dynamically

I am trying to change the columns collection of my Kendo grid in the below way.
var grid = $("#grid").data("kendoGrid");
$http.get('/api/GetGridColumns')
.success(function (data) {
grid.columns = data;
})
.error(function (data) {
console.log(data);
});
This is changing the column collection but not reflecting immediately in my grid. But when I try to perform some actions in the grid (like grouping), then my new column set is appearing.
Please let me know how can I achieve this.
Regards,
Dilip Kumar
You can do it by setting the KendoUI datasource, destroy the grid, and rebuild it
$("#load").click(function () {
var grid = $("#grid").data("kendoGrid");
var dataSource = grid.dataSource;
$.ajax({
url: "/Home/Load",
success: function (state) {
state = JSON.parse(state);
var options = grid.options;
options.columns = state.columns;
options.dataSource.page = state.page;
options.dataSource.pageSize = state.pageSize;
options.dataSource.sort = state.sort;
options.dataSource.filter = state.filter;
options.dataSource.group = state.group;
grid.destroy();
$("#grid")
.empty()
.kendoGrid(options);
}
});
});
here you can just do this :
var options = grid.options;
options.columns = state.columns;
where you can retrieve the columns in a session or in a db
This jsfiddle - Kendo UI grid dynamic columns can help you - using kendo.observable.
var columns = data;
var configuration = {
editable: true,
sortable: true,
scrollable: false,
columns: columns //set the columns here
};
var grid = $("#grid").kendoGrid(configuration).data("kendoGrid");
kendo.bind($('#example'), viewModel); //viewModel will be data as in jsfiddle
For the ones who are using Kendo and Angular together, here is a solution that worked for me:
The idea is to use the k-rebind directive. From the docs:
Widget Update upon Option Changes
You can update a widget from controller. Use the special k-rebind attribute to create a widget which automatically updates when some scope variable changes. This option will destroy the original widget and will recreate it using the changed options.
Apart from setting the array of columns in the GridOptions as we normally do, we have to hold a reference to it:
vm.gridOptions = { ... };
vm.gridColumns = [{...}, ... ,{...}];
vm.gridOptions.columns = vm.gridColumns;
and then pass that variable to the k-rebind directive:
<div kendo-grid="vm.grid" options="vm.gridOptions" k-rebind="vm.gridColumns">
</div>
And that's it when you are binding the grid to remote data (OData in my case). Now you can add or remove elements to/from the array of columns. The grid is going to query for the data again after it is recreated.
When binding the Grid to local data (local array of objects), we have to somehow postpone the binding of the data until the widget is recreated. What worked for me (maybe there is a cleaner solution to this) is to use the $timeout service:
vm.gridColumns.push({ ... });
vm.$timeout(function () {
vm.gridOptions.dataSource.data(vm.myArrayOfObjects);
}, 0);
This has been tested using AngularJS v1.5.0 and Kendo UI v2016.1.226.
I'm use this code for change columns dynamic:
kendo.data.binders.widget.columns = kendo.data.Binder.extend({
refresh: function () {
var value = this.bindings["columns"].get();
this.element.setOptions({ columns: value.toJSON });
this.element._columns(value.toJSON());
this.element._templates();
this.element.thead.empty();
this.element._thead();
this.element._renderContent(this.element.dataSource.view());
}
});
Weddin
Refresh your grid
.success(function (data) {
grid.columns = data;
grid.refresh();
})
Here is what i use
var columns = [];//add the columns here
var grid = $('#grid').data('kendoGrid');
grid.setOptions({ columns: columns });
grid._columns(columns);
grid._templates();
grid.thead.empty();
grid._thead();
grid._renderContent(grid.dataSource.view());
I think a solution for what you are asking is to call the equivalent remote DataSource.read() method inside of the function. This is what I used to change the number of columns dynamically for local js data.
$("#numOfValues").change(function () {
var columnsConfig = [];
columnsConfig.push({ field: "item", title: "Metric" });
// Dynamically assign number of value columns
for (var i = 1; i <= $(this).val(); i++) {
columnsConfig.push({ field: ("value" + i), title: ("201" + i) });
}
columnsConfig.push({ field: "target", title: "Target" });
columnsConfig.push({ command: "destroy", title: "" });
$("#grid").data("kendoGrid").setOptions({
columns: columnsConfig
});
columnDataSource.read(); // This is what reloads the data
});
Refresh the grid
$('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();
Instead of looping through all the elements. we can remove all the data in the grid by using a single statement
$("#Grid").data('kendoGrid').dataSource.data([]);
If your grid is simple and you don't need to configure special column-specific settings, then you can simply omit the columns argument, as suggested in the API reference.
Use autogenerated columns (i.e. do not set any column settings)
... and ....
If this [column] setting is not specified the grid will create a column for every field of the data item.
var newDataSource = new kendo.data.DataSource({data: dataSource}); $("#grid").data("kendoGrid").setDataSource(newDataSource);
$("#grid").data("kendoGrid").dataSource.read();
After fighting this for a day and seeing hints in this thread that Kendo had simplified this problem, I discovered you can just use setOptions with a single property.
.success(function (data) {
grid.setOptions({
columns: data,
});
})
Grid Set Options

Kendo UI grid - batch update not executed

I'm implementing a simple (at least ,that was the goal) Kendo UI grid that displays two columns: one holding a checkbox, bound to a boolean, and one holding a display name for the item. The checkbox column has a simple template, and the change() event of the checkbox is handled so that the model in the datasource gets updated. I have verified this, and it works.
The data source has been configured for batch, and defines a transport for read and update. Both call a function that perform the ajax call. As I said before, the read function is handled as expected. However, the update function defined on the transport is not. The sync() on the datasource is triggered with a simple button whose click event is hooked to a function that calls datasource.sync() (or grid.saveChanges()).
transport: {
read: function(options) {
return loadStuff(options);
},
update: function (options) {
return updateStuff(options);
}
}
When debugging in the Kendo UI code, it looks like the models attribute on the ModelSet is always empty, and therefore the sync() decides that there's nothing to sync. Anyone got a clue what is happening here?
UPDATE:
Looks like something may be wrong when handling the checkbox check / uncheck. Apparently I should use something like
$('#divGrid').on('click', '.chkbx', function() {
var checked = $(this).is(':checked');
var grid = $('#divGrid').data().kendoGrid;
var dataItem = grid.dataItem($(this).closest('tr'));
dataItem.set("Selected", checked);
});
Unfortunately, it looks like the set() method is not defined on the data item. When debugging, it only contains the data, and no Model object having the set() method.
UPDATE 2:
Tried wrapping the data returned from the ajax call in a model defined with Model.define(). That seems to solve the issue of the model not being dirty, as the _modified property on the model returns true. However, the models array in the ModelSet remains empty. Is this a bug in Kendo UI, or am I going the wrong way?
You don't actually need to bind to click event on the checkboxes.
I´ve posted an example on using it in JSFiddle where you can see it running. This example displays in a grid two columns: first text (tick) and second boolean rendered as a checkbox (selected); the update is batch (so, it's pretty close to what you have).
Questions to keep in mind are:
For displaying the checkbox while not in edit mode, you should define a template, something like this. You might realize that the checkbox is in disabled state by default since you want to edit it as other fields (selecting the cell first). This also guarantees that the model is correctly updated:
{
field : "selected",
title : "Selected",
template: "<input type='checkbox' name='selected' #= selected ? 'checked' : '' # disabled/>"
}
Define in the model that this field is boolean:
schema : {
id : "id",
model: {
fields: {
symbol : { type: "string" },
selected: { type: "boolean" }
}
}
},
Define the transport.update function, something like:
transport: {
read : function (operation) {
// Your function for reading
},
update: function (operation) {
// Display modified data in an alert
alert("update" + JSON.stringify(operation.data.models, null, 4));
// Invoke updating function
// that should ends with an operation.success(the_new_data)
// In this example just say ok
operation.success(operation.data.models)
}
}
EDIT: If you want to be able to modify the checkbox state without having to enter in edit mode first, you should:
Remove the disabled from the template:
{
field : "selected",
title : "Selected",
template : "<input type='checkbox' name='selected' #= selected ? 'checked' : '' #/>"
},
Then bind the click event on checkboxes to the following handler function:
$("#stocks_tbl").on("click", "input:checkbox", function(ev) {
var dataItem = grid.dataItem($(this).closest('tr'));
dataItem.set("selected", this.checked);
});
Where #stocks_tbl is the id of the div that contains the grid. You might see it running here.
NOTE: It's important the on with the three parameters for making it live

Resources