How to parse my JSON data to String in KENDO GRID? - laravel

how can i format this object Object to its actual values ?
I want this json object to display its actual values in a specific kendo grid column .
Can someone please help me and teach me how to do it ?
This is the image of the kendo grid with the result ,
While here is the code that I am using in my view .
Can please someone help .
contact : new kendo.data.DataSource({
transport:{
read:{
type: "GET",
url:"reservation/list",
dataType:"json",
contentType: "application/json; chartset=utf-8"
},
update: {
url: "contacts/update",
dataType: "json",
type: "POST"
},
destroy: {
url: "contacts/destroy",
dataType: "json",
type:"POST"
},
create: {
url: "contacts/store",
dataType: "json",
type:"POST"
}
},
schema:{
model:{
id:"id",
fields:{
Purpose:
{
type:"string",
validation:{required:true}
},
RoomID:
{
from: "RoomID.room_name",
type: "string"
},
Equipments:
{
from: "Equipments",
type: "string"
},
start:
{
type:"date",
validation:{required:true}
},
end:
{
type:"date",
validation:{required:true}
},
}
}
},
pageSize:10
}),
init : function(e){
$("#grid").kendoGrid({
dataSource: this.contact,
selectable: true,
height:600,
editable: "popup",
filterable: true,
sortable: {
mode: "multiple",
allowUnsort: true,
showIndexes: true
},
toolbar: ["search"],
columns: [
{
field: "Purpose",
title:"Purpose"
},
{
field: "RoomID",
title:"Room",
},
{
field: "Equipments",
title:"Equipments",
},
{
field: "start",
title:"Start",
//template: '#= kendo.toString(kendo.parseDate(start), "MM/dd/yyyy HH:mm:ss")#'
format: "{0:MMM dd,yyyy hh:mm tt}",
parseFormats: ["yyyy-MM-dd'T'HH:mm.zz"]
},
{
field: "end",
title:"End",
//template: '#= kendo.toString(kendo.parseDate(end), "MM/dd/yyyy HH:mm:ss")#'
format: "{0:MMM dd,yyyy hh:mm tt}",
parseFormats: ["yyyy-MM-dd'T'HH:mm.zz"]
},
{
command: ["edit", "destroy"],
title: " ",
width: "250px"
}
],
pageable:{
pageSize:10,
refresh:true,
buttonCount:5,
messages:{
display:"{0}-{1}of{2}"
}
}
});
},
});
kendo.bind($("#whole"),model);
model.init();

Hopefully this will help you out with templating out the results.
https://dojo.telerik.com/ICOceLUj
In the example above I have created a custom column that takes the incoming row object and then parsed the name of the item and the category object into a single template.
To achieve this I have added the template property and used a function with an external template script to handle the manipulation. I personally find this easier to manage than trying to inline a complex client template (especially if you have logic involved)
So this is how we set it up initially:
{ title: "custom template", template:"#=customTemplate(data)#" }
obviously you will change it to the property you need to look at in your model.
then the function is a couple of lines of code:
function customTemplate(data){
var template = kendo.template($('#customTemplate').html());
var result = template(data);
return result;
}
so this takes the customTemplate template i have created for this and renders it as html and then it will apply the data where appropriate. The template looks like this:
<script id="customTemplate" type="text/x-kendo-template">
<div>
<h5> #:data.ProductName#</h5>
<h4>#: JSON.stringify(data.Category, null, 4) #</h4>
</div>
</script>
You can then customize this template to how you need it to look for your specific needs. You can then either create a source template for the items and then map the values back as single string or have the logic for this in the template. Which ever is most sensible in your case.
For more info on templating please look at this link:
https://docs.telerik.com/kendo-ui/framework/templates/overview

You can use kendo.stringify in your column template.
Example:
kendo.stringify(YourProperty)

Related

How to get value id from dataSource by row Kendo UI Grid

Help me code How to get value id from dataSource by row and change to current value default (1)
in line: var date = dataSource.get(1);
console.log(date.ProductName)
My full source:
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
selectable: true,
pageable: true,
height: 550,
toolbar: ["create"],
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "120px" },
{ field: "UnitsInStock", title:"Units In Stock", width: "120px" },
{ field: "Discontinued", width: "120px", editor: customBoolEditor },
{ command: ["edit", "destroy"], title: " ", width: "250px" }],
editable: "inline",
edit: function () {
var date = dataSource.get(1);
console.log(date.ProductName)
}
});
});
</script>
Now, when click edit, all rows only get fields of id 1. I want corresponding id instead of the default id 1.
edit
Fired when the user edits or creates a data item.
The event handler function context (available via the this keyword)
will be set to the widget instance.
EVENT DATA
e.container jQuery The jQuery object of the edit container
element, which wraps the editing UI. Depending on the Grid edit mode,
the container is different:
"incell" edit mode - the container element is a table cell
"inline" edit mode - the container is a table row
"popup" edit mode - the container is a Kendo UI Window element, which provides an easy way to obtain a reference to the Window widget object, e.g. to attach additional events.
e.model kendo.data.Model The data item which is
going to be edited. Use its isNew method to check if the data item is
new (created) or not (edited).
e.sender kendo.ui.Grid The widget instance which fired the event.
$("#grid").kendoGrid({
columns: [
{ field: "id" },
{ field: "name" },
{ field: "age" },
{ command: "edit" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: {
id: "id",
fields: {
"id": { type: "number" }
}
}
}
},
editable: "popup",
toolbar:["create"],
edit: function(e) {
console.log(e.model.id);
console.log(e.model.name);
}
});
Working example: edit event
Documentation: grid edit event

How to get field value when edit data in Kendo Ui treelist

I'm new in Kendo UI,and i have a question. Now i'm use TreeList / Editing and how to auto load value to other field when i edit value to first field ?
example:
1.serial number: 123456789
2.name : test
when i edit serial number 123456789 to first field and auto load name to second field.
To set the value of column B based on change made to a column A, you need to edit the model bound to the tree list. For this do the following:-
Handle edit event of the tree list. On this save the model to a
local variable.
Add an editor
template
to column A. On the select event set the value of model.
Below is a working code snippet:-
<div id="treelist"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service";
var model= null;
var employeesData=[{"EmployeeId":101,"FirstName":"Daryl","LastName":"Sweeney"},
{"EmployeeId":202,"FirstName":"Guy","LastName":"Wooten"},
{"EmployeeId":303,"FirstName":"Priscilla","LastName":"Frank"},
{"EmployeeId":404,"FirstName":"Ursula","LastName":"Holmes"},
{"EmployeeId":505,"FirstName":"Anika","LastName":"Vega"}];
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/EmployeeDirectory/All",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
schema: {
model: {
id: "EmployeeId",
parentId: "ReportsTo",
fields: {
EmployeeId: { type: "number", nullable: false },
ReportsTo: { nullable: true, type: "number" },
FirstName: { validation: { required: true } },
HireDate: { type: "date" },
Phone: { type: "string" },
HireDate: { type: "date" },
BirthDate: { type: "date" },
Extension: { type: "number", validation: { min: 0} },
Position: { type: "string" }
},
expanded: true
}
}
});
$("#treelist").kendoTreeList({
dataSource: dataSource,
toolbar: [ "create", "save", "cancel" ],
editable: "incell",
height: 540,
dataBound: function (e) {
var items = e.sender.items();
for (var i = 0; i < items.length; i++) {
var dataItem = e.sender.dataItem(items[i]);
var row = $(items[i]);
if (dataItem.isNew()) {
row.find("[data-command='createchild']").hide();
}
else {
row.find("[data-command='createchild']").show();
}
}
},
edit: function(e) {
model = e.model;
},
columns: [{
field: "EmployeeId",
expandable: true,
title: "Serial Number",
width: 180,
editor: function(container, options) {
// create an input element
var input = $("<input/>");
// set its name to the field to which the column is bound ('lastName' in this case)
input.attr("name", options.field);
// append it to the container
input.appendTo(container);
// initialize a Kendo UI AutoComplete
input.kendoAutoComplete({
dataTextField: "EmployeeId",
dataSource: employeesData,
select: function(e) {
if(model !=null){
model.FirstName = e.dataItem.FirstName;
model.LastName = e.dataItem.LastName;
}
}
});
}
},
{ field: "FirstName", title: "First Name", width: 100 },
{ field: "LastName", title: "Last Name", width: 100 },
{ field: "Position", width: 100 },
{ field: "Phone", title: "Phone", width: 100 },
{ field: "Extension", title: "Ext", format: "{0:#}", width: 100 },
{ command: [{name: "createchild", text: "Add child"},"destroy" ], width: 240 }]
});
});
</script>
You can trigger your function when the row is being saved or when the edit field is being changed. Take a look at the list of events here and choose when exactly you want to make the changes. https://demos.telerik.com/kendo-ui/treelist/events
here is a example how to all a function when saving the changes: https://docs.telerik.com/kendo-ui/api/javascript/ui/treelist/methods/saverow
I´m not sure witch edit method you are using (inline, inCell or Popup edit mode) each method can use events like saveRow, beforeEdit...
Check all the events documentation here: https://docs.telerik.com/kendo-ui/api/javascript/ui/treelist#events

Kendo Grid Serverside Paging, Incorrect Parameter Map values

I'm trying to use the Dynamic Linq Helper libraries from Kendo. The parameter map function on the grid does not have the correct parameters to send to the controller.
The parameterMap options have:
{"take":10,"skip":0,"page":1,"pageSize":10}
but according to the example, it should have take, skip, sort, filter, which is not in the parameterMap function or getting passed to the server.
I'm following the example here
http://www.telerik.com/blogs/kendo-ui-open-sources-dynamic-linq-helpers
And also looked other examples, my grid is set up the same as the others.
The only difference being, this is a Web API single page app, not MVC. However, this shouldn't make a difference in what the Grid class is passing to it's parameterMap function.
What is going on here?
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "http://localhost/biahost/query/projectStatuses",
dataType: "application/json",
type: "POST",
contentType: "application/json; charset=utf-8"
//data:{}
},
parameterMap: function (options) {
debugger;
//options only contain {"take":10,"skip":0,"page":1,"pageSize":10}
return kendo.stringify(options);
}
},
schema: {
data: "Data",
total: "Total",
model: {
fields: {
NAME: { type: "string" },
CODE: { type: "string" },
STATUS: { type: "string" },
COMMENTS: { type: "string" },
INSERTS: { type: "string" },
UPDATES: { type: "string" },
TOTAL_UPDATES: { type: "string" },
LAST_ACTION_DATE: { type: "string" }
//UnitId: { type: "string" },
//UnitName: { type: "string" }
}
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
filterable: true,
sortable: true,
pageable: true,
columns: projectStatusColumns
});
var projectStatusColumns = [
{
field: 'NAME',
label: 'Res name',
hidden: true,
},
{
field: 'CODE',
label: 'Code'
},
{
field: 'STATUS',
label: 'Status'
},
{
field: 'COMMENTS',
label: 'Comments'
}
,
{
field: 'INSERTS',
label: 'Inserts'
}
,
{
field: 'UPDATES',
label: 'Updates'
}
,
{
field: 'TOTAL_UPDATES',
label: 'Total Updates'
}
,
{
field: 'LAST_ACTION_DATE',
label: 'Last Action Date'
}
];
had the same problem so i looked it up and here i am. You just need to return "options" which contains the parameter map as it is, if you stringify it will become a json object which cannot be defined in a url.
Hope i'm not too late!

Kendo Grid renders properly but does not display json data

I have been having a tough time with grids lately, mostly getting them to display properly formatted JSON data that is being fetched from a webservice (which has been checked in VS2013, and JSONLint), if a second set of eyes could please have a look at my solution and tell me whats lacking? I am going bananas!
function SetTelerikGrid() {
// prepare the data object and consume data from web service,...
$.ajax({
type: "GET",
async: false,
url: "http://localhost:38312/SDMSService.svc/GetProductPositionsByLocation/0544",
datatype: "json",
success: function (ProductData, textStatus, jqXHR) {
// populate kendo location grid by data from successful ajax call,...
$("#LocationProductsGrid").kendoGrid({
dataSource: {
data: ProductData, // solution here was: **JSON.parse(LocationData)**
schema: {
model: {
fields: {
Date: { type: "string" },
ProductCode: { type: "string" },
StoreNum: { type: "string" },
ProductQty: { type: "int" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: true,
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false
},
columns: [
{ field: "Date", title: "Date", width: "130px" },
{ field: "ProductCode", title: "Product Code", width: "130px" },
{ field: "StoreNum", title: "Store Number", width: "130px" },
{ field: "ProductQty", title: "Product Qty", width: "130px" }
]
});
}
});
}
There is a breaking change in ASP.NET Core, related to how the JSON serializer
works
You can probably mitigate this by adding a json option like this:
1:
change
services.AddMvc();
to
services
.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
OR
2:
public IActionResult Read()
{
// Override serializer settings per-action
return Json(
MyModel,
new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() }
);
}
refrences :
http://www.telerik.com/forums/using-2016-2-630-preview---data-not-displayed#qlHR6zhqhkqLZWuHfdUDpA
https://github.com/telerik/kendo-ui-core/issues/1856#issuecomment-229874309
https://github.com/telerik/kendo-ui-core/issues/1856#issuecomment-230450923
Finally figured it out, the 'ProductData' field - although in perfect JSON format - still required to be parsed as JSON in the datasource configuration, like so,...
Data: JSON.parse(ProductData)

Get all updated and newly created models together in a single url in server side

I am Using Kendo grid with batch edit. I want to get all Modified and newly created models together in a single url.
Say I have created 3 new row and also updated/edited 2 existing row in grid. Data source makes a HTTP request for every CRUD operation . The changed data items are sent by default as models and hit URL as I declared in “create” and update (transport) section of transport in datasource.I am getting models those are Modified (updated) in URL declared for ‘update’ in server side. And also find models those are newly created in URL declared for ‘create’….But I want to get all Modified and newly created models together in a single url.Is it possible to get all of the (both all modified and newly created) in a single URL?
Here is my Code for better understand.
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "LoadPerMeterCostsGridData",
type: "POST",
contentType: "application/json",
dataType: "json"
},
update: {
url: "UpdatePerMeterCostsData",
contentType: "application/json",
type: "POST",
dataType: "json"
},
create: {
url: "CreatePerMeterCostsData",
contentType: "application/json",
type: "POST",
dataType: "json",
},
parameterMap: function (data, operation) {
if (operation != "read") {
return kendo.stringify(data.models);
}
}
},
serverPaging: false,
pageSize: 10,
batch: true,
schema: {
model: {
id: "PerMeterCostID",
fields: {
PerMeterCostID: { editable: false },
DrillBitSizeID: { editable: true },
Form: { editable: true },
To: { editable: true },
PerMeterCost: { editable: true },
ContractID: { editable: false }
}
},
errors: "Errors"
},
error: function (e) {
alert(e.errors + "grid");
}
},
editable: true,
pageable: {
refresh: true,
pageSizes: true
},
toolbar: ["create",
"save",
"cancel"
],
sortable: true,
autoBind: false,
columns:
[
{ field: "PerMeterCostID", width: 50, hidden: true, title: "ID" },
{ field: "DrillBitSizeID", width: 100, hidden: true, title: "Consumable" },
{ field: "Form", width: 100, title: " Form " },
{ field: "To", width: 50, title: "To" },
{ field: "PerMeterCost", width: 100, title: "Per Meter Cost" },
{ field: "ContractID", width: 100, hidden: true, title: "ContractID" },
{ command: ["destroy"], title: "Action", width: "175px" }
]
});
$("#grid ").data("kendoGrid").dataSource.read();
You can set each CRUD action to use the same url, but using the same url: property for both Create and Update. However you will still minimally get TWO requests (albeit to the same url)
update: {
url: "UpdateOrCreateAction",
},
create: {
url: "UpdateOrCreateAction",
},
this is because internally the dataSource pushes all "new" items as defined by "items an Id Field set to the default value for the field" in an array, and all items with dirty set to true into a different array. Kendo then sends both arrays back to the server according to the url for the action. (something like this i'd imagine)
if ( model.isNew())
createdPile.push(model)
else if ( model.dirty === true)
updatedPile.push(model)
//send both piles to the server
The "easiest" way to avoid this is to make sure your new objects explicitly set their id fields to something other then the default, and set the models dirty prob to true.
you could do this by using the edit event to override the actions
grid.bind('edit', function(e){
if ( e.model.isNew() ) {
e.model.id = -1; //
e.dirty = true;
console.log(e.model.isNew()) // should be false
}
})
this is probably an extreme amount of overkill to avoid one additional request, and prone to error. I would advise that you use the same url for both actions, and just accept that you will get the created items in one batch, and the updated in another.

Resources