Why parameterMap is not calling in KendoGrid? - kendo-ui

have the following kendo grid:
this.kGrid = $element.kendoGrid({
columns: [
{ field: 'Title' },
{ field: 'Description' },
{
field: 'StartDate',
title: 'Start Date',
template: `#= kendo.toString(kendo.parseDate(DistributionDate), "${DATE_FORMAT} ${TIME_FORMAT}")#`,
}
],
filterable: true,
dataSource: {
type: 'aspnetmvc-ajax',
transport: {
read: {
url: '/Pubs/GetPubs',
dataType: "json",
type: 'POST',
data: () => ({
collectionId: this.selectedCollection,
categoryUid: this.selectedCategory
})
},
parameterMap: function (data, type) {
//i wawnt to add some logic here to convert StartDate from local time to UTC
}
},
serverFiltering: true,
schema: {
data: 'Data',
total: 'Total',
model: {
id: 'Uid',
fields: {
Title: { type: 'string' },
Description: { type: 'string' },
StartDate: { type: 'date' }
}
}
}
}
}).data('kendoGrid');
So i have a grid with 3 columns and all of them are filterable. My goal is to convert the date in the filter for StartDate from local time to UTC. That's why i added parameterMap handler. But for some reason, parameterMap method is not called at all. What i'm doing wrong here?
Here is full code snippet - https://dojo.telerik.com/IqadArAn/3. But the problem is not reproducible here
EDIT: It seems that problem is in dataSource type, which is 'aspnetmvc-ajax'. If to change the dataSource type, parameterMap works.

The alternative solution is to:
Skip setting the transport type
Implement custom read method
This questions describes the similar issue - https://www.telerik.com/forums/datasource-transport-function-mode-read-and-wrong-request-parameters.
Here is the code of custom read method, which should be placed inside of dataSource.transport.
read: (optionsData) => {
if (optionsData.data.filter) {
optionsData.data.filter.filters.forEach((item) => {
if (item.field === "StartDate") {
item.value = item.value.toISOString();
}
});
}
var data = kendo.data.transports["aspnetmvc-ajax"].prototype.options.parameterMap.call({ options: { prefix: "" }}, optionsData.data, "read", false);
data.encryptedCollectionId = this.selectedCollection;
data.categoryUid = this.selectedCategory;
$.ajax({
type: "POST",
url: 'Pubs/GetPubs',
data: data
})
.then(
function succes(res) {
optionsData.success(res);
},
function failure(res) {
optionsData.error(res);
}
);
}

Related

Using fetch method inside Kendo UI grid.template

How to return value from .fetch() method inside grid.template ?
$("#grid-single-user-groups").kendoGrid({
dataSource: assignedUsersDataSource,
toolbar: ["create"],
columns: [
{
field: "UserID", width: "100%",
editor: userDropDownEditor,
template: function(userID) {
//here I can return everything, and its visible in grid cell
//return "BAR"
allUsersDataSource.fetch(function() {
//Here everything is UNDEFINED
return "FOO";
var data = this.data();
console.log(data.length);
for (var idx = 0, length = data.length; idx < length; idx++) {
console.log(data.length); //show right length
console.log(data[idx].UserName);// //show right UserName
if (data[idx].UserNameID === userID.UserID) {
return userID.Login; //UNDEFINED
//return "foo"; //UNDEFINED
}
})
edit:
allUsersDataSource is Kendo DataSource:
var allUsersDataSource = new kendo.data.DataSource({
transport: {
read: {
url: API_URL + "frank/getusers",
dataType: "json"
}
},
});
results JSON:
[{"UserNameID":"2","UserName":"foo","Surname":"foo2","Login":"foo3","GroupName":"admin"},]
edit2:
trying with read() function instead od fetch, with below code:
template: function(userID) {
allUsersDataSource.read().then(function() {
var view = allUsersDataSource.view();
console.log(view[0].Login)// displays right Login
return view[0].Login; // displays "undefined" in grid cell
});
}
edit3:
My entire code where I whant to use DropDown inside Grid cell:
var allUsersDataSource = new kendo.data.DataSource({
transport: {
read: {
url: API_URL + "frank/getusers",
dataType: "json"
}
},
});
allUsersDataSource.fetch(function() {
allUsers = allUsersDataSource.data();
})
var assignedUsersDataSource = new kendo.data.DataSource({
transport: {
read:{
url: API_URL+"frank/getassignedusers/"+documentId,
dataType: "json"
},
create: {
type: "POST",
url: API_URL+"frank/addusertodocument",
dataType: "json"
},
destroy:{
type: "POST",
url: API_URL+"frank/removeuserdocument",
dataType: "json"
},
},
pageSize: 4,
schema: {
model: {
fields: {
UserName: { editable: false, nullable: true },
Surname: { editable: false, nullable: true },
UserID: { field: "UserID", defaultValue: 1 },
GroupName: { editable: false, nullable: true },
}
}
}
});
$("\#grid-single-user-groups").kendoGrid({
dataSource: assignedUsersDataSource,
filterable: true,
scrollable: false,
toolbar: ["create"],
pageable: true,
columns: [
{
field: "UserID", width: "100%",
editor: userDropDownEditor,
title: "Agent",
template: function(userID) {
for (var idx = 0, length = allUsers.length; idx < length; idx++) {
if (allUsers[idx].UserNameID === userID.UserID) {
return userID.Login;
}
}
}
},
{ command: "destroy" }
],
editable: true,
remove: function(e) {
console.log("Removing", e.model.name);
}
});
function userDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataTextField: "Login",
dataValueField: "UserNameID",
filter: "contains",
dataSource: allUsersDataSource
})
}
JSON DataSources - assignedUsersDataSource:
[{"UserID":"198","UserName":"Paw","Surname":"yui","Login":"ddz","GroupName":"ddd"},...]
JSON DataSources - allUsersDataSource:
[{"UserNameID":"198","UserName":"Paw","Surname":"yui","Login":"ddz","GroupName":"ddd"},...]
edit4:
corrected sample datasource:
var assignedUsersDataSource = new kendo.data.DataSource({
data: [{"UserID":"198","UserName":"Paw","Surname":"Mu","Login":"pc","GroupName":"ad"}]
});
var allUsers = new kendo.data.DataSource({
data: [{"UserNameID":"198","UserName":"Paw","Surname":"Mu","Login":"pc","GroupName":"ad"},{"UserNameID":"199","UserName":"Jakub","Surname":"Ch","Login":"jc","GroupName":"ki"}]
});
So to avoid cluttering up the comments here is a possible answer to your problem:
http://dojo.telerik.com/INukUVoT/4
If you now select the item from the dropdown it is changing the id as it retains the last selected item in the selection when you go in and out of it. The reason the name stays the same is a simple one. It's looking in the wrong place for the value to display.
You are simply doing the following:
Look at all the values in the allusers store and then if i get a match of id's just show the value in the model's Login value rather than the value that was found in the data item in the Login.
So you are currently going through a needs loop. you literally could change your template to:
template: "#=data.Login#" rather than having to loop around.
what you seemingly want to do is have one column which is a user object or defined as an id either way will work as you can see in my new examples.
the first grid is binding the UserID property to the grid and then presenting back the value from the dropdown's datasource (you need to ensure that you set the valuePrimitive property to true so it binds only the value and not the object.
the second grid binds the full object and just so you see what is being bound i am stingify'ing the object and putting that into the grid.

Kndo TreeView LoadOnDemand not hitting the server

for my kendo treeview, i set load on demand to true but it is not hitting the server to load childs, because the 'children' property is set for the datasource model, even its empty.
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
type: 'POST',
contentType: "application/json; charset=utf-8",
url: obj.DataSourcesURL,
dataType: "json"
},
parameterMap: function (options) {
if (!options.Id) {
options.Id = null;
}
if (options.filter) {
options.Search = options.filter.filters[0].name;
}
else {
options.Search = '';
}
return JSON.stringify(options);
}
},
schema: {
data: "d",
errors: function (response) {
console.log(response);
console.log("errors");
},
model: {
hasChildren: "hasChild",
children:'items',
id: "Id"
}
}
});
And treeView code is
$treeView.kendoTreeView({
dataTextField: 'Description',
checkboxes: {
checkChildren: true
},
dataSource: homogeneous,
loadOnDemand: loadOnDemand,
check: function () {
var checkedNodes = [];
var treeView = $treeView.data("kendoTreeView");
getCheckedNodes(treeView.dataSource.view(), checkedNodes);
setMessage(checkedNodes.length);
},
dataBound: function (e) {
if (e !== undefined)
resetCheckedNodes(e.sender.dataItems());
},
messages: {
loading: "Laden..."
},
expand: function (e) {
var dataItem = this.dataItem(e.node);
}
});
Try to set hasChildren like this in your schema:
schema: {
data: "d",
errors: function (response) {
console.log(response);
console.log("errors");
},
model: {
hasChildren: function(e) {
return e.items && e.items.length;
},
children:'items',
id: "Id"
}
}
And also from your question I am not sure do you even get any data or it is only Children data that is not returned. Maybe you could also show how your data structure look like.

Change Kendo Grid Cell With Ajax Response When Another Cell Changes

Using a Kendo grid with 3 columns, I have an event that fires when the first column is changed that makes an ajax call and returns some data. I want to update the second column with the returned data but I'm not having any luck and I'm not even sure if this is the correct approach. I can change the second column with static data by adding a change event to my datasource of my grid, but that of course doesn't help. The only examples I can seem to find show changing another column with client side data, not data returned from the server. Here's what I have so far:
$("#manualStatsGrid").kendoGrid({
dataSource: this.GetManualStatisticsDataSource(),
sortable: true,
pageable: false,
filterable: true,
toolbar: ["create"],
editable: "inline",
messages: {
commands: {
create: "Add New Statistic"
}
},
edit: function (e) {
var _this = _manualStats;
var input = e.container.find(".k-input");
var value = input.val();
input.keyup(function(){
value = input.val();
});
$("[name='Statistic']", e.container).blur(function(){
var input = $(this);
$("#log").html(input.attr('name') + " blurred " + value);
//valid the GL account number
$.ajax({
type: "GET",
url: _this.ValidateGlUrl,
dataType: 'json',
data: { glNumber: value },
success: function (response) {
var newDescription = response.Data.description;
console.log(newDescription);
//change description column here?
},
error: function (response) {
console.log(response);
}
});
});
},
columns: [
{ field: "Statistic" },
{ field: "Description" },
{ field: "Instructions" },
{ command: ["edit", "destroy"], title: " ", width: "250px"}
]
});
}
this.GetManualStatisticsDataSource = function () {
var _this = _manualStats;
var dataSource = {
type: "json",
transport: {
read: {
type: "POST",
url: _this.GetManualStatisticsUrl,
dataType: "json"
},
update: {
type: "POST",
url: _this.UpdateManualStatisticsUrl,
dataType: "json"
},
create: {
type: "POST",
url: _this.CreateManualStatisticsUrl,
dataType: "json"
},
destroy: {
type: "POST",
url: _this.DeleteManualStatisticsUrl,
dataType: "json"
}
},
schema: {
model: {
id: "Statistic",
fields: {
Statistic: {
type: "string",
editable: true,
validation: { required: true, pattern: "[0-9]{5}.[0-9]{3}", validationmessage: "Please use the following format: #####.###" }
},
Description: { editable: false },
Instructions: { type: "string", editable: true }
}
}
}
Inside the edit event, you have e.model. The model has the method set() which can change any dataItem's property value:
edit: function (e) {
...
var editEvent = e; // Creates a local var with the edit's event 'e' variable to be available inside the 'blur' event
$("[name='Statistic']", e.container).blur(function() {
...
$.ajax({
...
success: function(e, response) { // 'e' inside this callback is the 'editEvent' variable
e.model.set("Description", response.Data.description); // e.model.set() will change any model's property you want
}.bind(null, editEvent) // Binds the 'editEvent' variable to the success param
});
});
Working demo
Made this snippet of top of my head. Tell me if there is something wrong with it.

How to make the method getItem from the offlineStorage of the Kendo Datasource work with LocalForage

I need to setup my datasource to use localForage to manage my offline data storage.
The problem I'm having is that localForage is asynchronous by nature, only allowing us to use a callback or a promise to retrieve data.
This is how my code is set-up:
(function () {
'use strict';
var serviceId = 'employeeDataSource';
angular.module('app').factory(serviceId, function () {
var crudServiceBaseUrl = 'Data/Employees';
var dataSource = new kendo.data.DataSource({
type: "odata",
offlineStorage: {
getItem: function () {
localforage.getItem('employees-key').then(function (value) {
console.log(value);
return JSON.parse(value);
});
},
setItem: function (item) {
if (item.length > 0) {
localforage.setItem("employees-key", JSON.stringify(item));
}
}
},
transport: {
read: {
url: crudServiceBaseUrl + "/",
dataType: "json"
},
update: {
url: function (data) {
return crudServiceBaseUrl + "(guid'" + data.EmployeeId + "')";
}
},
create: {
url: crudServiceBaseUrl
},
destroy: {
url: function (data) {
return crudServiceBaseUrl + "(guid'" + data.EmployeeId + "')";
}
}
},
batch: false,
pageSize: 5,
serverPaging: true,
schema: {
data: function (data) {
return data.value;
},
total: function (data) {
return data['odata.count'];
},
model: {
id: "EmployeeId",
fields: {
EmployeeId: { editable: false, nullable: true },
Name: { validation: { required: true } },
Email: { validation: { required: true } },
IsManager: { type: "boolean" },
MaxHolidaysPerYear: { editable: false, type: "number", validation: { min: 0, required: true } },
HolidaysLeftThisYear: { type: "number", validation: { min: 0, required: true } }
}
}
},
error: function (e) {
if (e.xhr.responseText !== undefined) {
console.log(e.xhr.responseText);
}
}
});
dataSource.online(navigator.onLine);
$(window).on("offline", function () {
dataSource.online(false);
});
$(window).on("online", function () {
dataSource.online(true);
});
return dataSource;
});
})();
When off-line, the getItem gets called, then the setItem gets call as well with an empty array, hence the:
if (item.length > 0) {
localforage.setItem("employees-key", JSON.stringify(item));
}
When the promise finally returns the off-line data (with the correct values I expected), the Grid displays no results.
This behaviour is presumably because of the promise ?
I tried the same thing with sessionStorage and its worked perfectly... i.e.:
getItem: function () {
return JSON.parse(sessionStorage.getItem("employees-key"));
},
setItem: function (item) {
sessionStorage.setItem("employees-key", JSON.stringify(item));
}
What can I do to get around this?
Just got a heads-up from Telerik
There is an issue logged in their GitHub repo about the same problem.
You can keep track on the progress here:
https://github.com/telerik/kendo-ui-core/issues/326

Change data sent to server for related data on update using kendo.datasource?

I am using the $expand to get related data which works fine but I need to change the data that is sent back
to the server when the data is updated
Example if my Server Side Data Model contains two entities
Contact
ID: number
firstName: string
middleName: string
lastname: string
ContactType: ContactType n-1
ContactType
ID: nubmer
name: string
ContactCollection: ContactType 1-n
Here is my datasource code
function GetContactDS(){
var MyModel = kendo.data.Model.define({
id: "ID",
fields: {
__KEY: { type: "string" },
__STAMP: { type: "number" },
ID: { editable: false, nullable: true },
firstName: { type: "string" },
middleName: { type: "string" },
lastName: { type: "string" }
},
});
var crudServiceBaseUrl = "http://127.0.0.1:8081/cors/Contact";
var MyDataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax( {
url: crudServiceBaseUrl + '/?$expand=ContactType',
dataType: "json",
data: options.data,
success: function(result) {
options.success(result);
}
});
},
update: function(options) {
$.ajax( {
url: crudServiceBaseUrl + "/?$method=update",
type: "POST",
dataType: "json",
data: kendo.stringify(options.data.models),
success: function(result) {
// notify the DataSource that the operation is complete
options.success(result);
}
});
},
destroy: {
url: crudServiceBaseUrl + "/?$method=delete",
type: "GET"
},
create: {
url: crudServiceBaseUrl + "/?$method=update",
dataType: "json",
type: "POST"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return JSON.stringify({"__ENTITIES": options.models});
}
}
},
batch: true,
pageSize: 30,
schema: {
model: MyModel,
data: "__ENTITIES"
}
});
return MyDataSource;
}
The read request returns this data
{"__entityModel":"Contact","__COUNT":1,"__SENT":1,"__FIRST":0,"__ENTITIES":[{"__KEY":"7","__STAMP":9,"ID":7,"firstName":"jay","middleName":"a","lastName":"blue","ContactType":{"__KEY":"2","__STAMP":4,"ID":2,"name":"Home","contactCollection":{"__deferred":{"uri":"/rest/ContactType(2)/contactCollection?$expand=contactCollection"}}}}]}
Here is the code calling read and binding to grid
var ContactDS = GetContactDS();
$("#grid").kendoGrid({
selectable: "row",
filterable: true,
pageable: true,
sortable: true,
change: function(){
datamodel = this.dataItem(this.select());
ID = datamodel.ID
},
dataSource: ContactDS,
columns: [
{ field: "ID" },
{ field: "firstName" },
{ field: "middleName" },
{ field: "lastName" },
{field: "ContactType.name"}
]
});
Which works fine I am getting the expanded info for ContactType in my datasource and it binds to a grid fine.
Now I want to update the after it the selected data row is read into a form, reading the data into the form works fine.
The problem is sending the update back to the server which expects a slightly different format for the related entity ContactType
It only needs the changed value of "__Key" to update
Here is my update function:
$("#update").click(function () {
datamodel.set("firstName", $("#firstName").val());
datamodel.set("lastName", $("#lastName").val());
datamodel.set("middleName", $("#middleName").val());
// datamodel.set("ContactType.__KEY",3);
ContactDS.sync();
Here is the data that the server expects
{ "__ENTITIES": [{"__KEY":"7","__STAMP":14,"firstName":"jay","middleName":"a","lastName":"red","ContactType":{"__KEY":"2"}}]}
Here is what kendo.datasource is sending
[{"__KEY":"7","__STAMP":12,"ID":7,"firstName":"jay","middleName":"a","lastName":"blue","ContactType":{"__KEY":"3","__STAMP":2,"ID":3,"name":"Work","contactCollection":{"__deferred":{"uri":"/rest/ContactType(3)/contactCollection?$expand=contactCollection"}}}}]
So how do I either reformat the data or define my model or datasource options to make sure that the extra ContactType fields are removed just leaving the updated "_KEY:" as well as wrapping the whole request in { "_ENTITIES":}
Thanks for any help!
Dan
You could try to use the parameterMap function to format the data in the way you need.
I think I found the answer from this post
It explains a little more on using parameterMap. If you look at the kendoui docs on parameterMap it seems to indicate that this is only for managing parameters like
pageIndex,size,orderBy ect. But from the above post it shows you how to delete a related entity or you can just delete or modify the fields of an entity or related entity
Example I can delete just the ContactTypeID of the related entity ContactType
parameterMap: function(options, operation) {
if (operation == "create") {
return JSON.stringify({"__ENTITIES": options.models});
}
else if (operation == "update") {
debugger;
delete options.models[0].ContactType.ID;
return JSON.stringify({"__ENTITIES": options.models});
}
}
Still have some work to do but I think this will get me there
Thanks Pechka for your help

Resources