Kendo Grid update jquery - javascript

I have a kendo grid with dynamic buttons, so after update I need to reload the grid to show/hide buttons, but it's not working :(
Here's my grid:
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "/CentroCusto/Lista",
dataType: "json",
cache: false
},
update: {
url: "/CentroCusto/Salvar",
contentType: "application/json",
dataType: "json",
cache: false,
complete: function (data) {
if (data.status == 500) {
alert('Ocorreu um erro ao salvar o registro.');
}
else {
$("#grid").data("kendoGrid").dataSource.read();
}
}
},
parameterMap: function (options, operation) {
if (operation == "update") {
return { models: kendo.stringify(options) };
}
}
},
schema: {
model: {
id: "Id",
fields: {
Id: { type: "number" },
Codigo: { type: "string", editable: false },
Descricao: { type: "string", editable: false },
Empresa: { type: "string", editable: false },
AprovadorId: { type: "number", editable: false },
NomeAprovador01: { type: "string", editable: true, validation: { required: true } },
PercentualLimite: { type: "number", editable: true, validation: { required: true, max: 100 } },
Status: { type: "string", editable: false },
AprovadorN01: { defaultValue: 1, field: "AprovadorN01" },
AprovadorN02: { defaultValue: 1, field: "AprovadorN02" },
AprovadorN03: { defaultValue: 1, field: "AprovadorN03" },
AprovadorN04: { defaultValue: 1, field: "AprovadorN04" },
NomeAprovador02: { type: "string", editable: false },
Aprovador03: { type: "number", editable: true, validation: { required: false } },
NomeAprovador03: { type: "string", editable: true, validation: { required: true } },
Aprovador04: { type: "number", editable: true, validation: { required: false } },
NomeAprovador04: { type: "string", editable: true, validation: { required: true } }
}
}
},
pageSize: 20,
serverPaging: false,
serverFiltering: false,
serverSorting: false
},
height: 450,
selectable: true,
filterable: true,
sortable: true,
pageable: true,
dataBound: gridDataBound,
columns: [{ field: "Codigo", title: "Código" },
{ field: "Descricao", title: "Descrição" },
{ field: "Empresa", title: "Empresa" },
{ field: "AprovadorN01", title: "Aprovador N01", editor: aprovadorDropDown, template: "#=AprovadorN01.Nome#" },
{ field: "AprovadorN02", title: "Aprovador N02", editor: aprovador02DropDown, template: "#=AprovadorN02.Nome#" },
{ field: "AprovadorN03", title: "Aprovador N03", editor: aprovador03DropDown, template: "#=AprovadorN03.Nome#" },
{ field: "AprovadorN04", title: "Aprovador N04", editor: aprovador04DropDown, template: "#=AprovadorN04.Nome#" },
{ field: "PercentualLimite", title: "% Limite", width: "10%", format: "{0:n}" },
{ field: "Status", title: "Status", width: "10%" },
{
command: [
{
name: "edit",
text: { edit: "Ativar", update: "Salvar", cancel: "Cancelar" },
className: "btn-successo",
imageClass: 'glyphicon glyphicon-remove-circle'
},
{
name: "inativar",
text: "Inativar",
className: "btn-excluir",
click: Inativar,
imageClass: 'glyphicon glyphicon-remove-circle'
},
{
name: "edit",
text: { edit: "Alterar", update: "Salvar", cancel: "Cancelar" },
className: "btn-alterar"
}
]
, width: "180px"
}
],
editable: {
update: true,
mode: "popup"
},
cancel: function (e) {
$("#grid").data("kendoGrid").dataSource.read();
},
edit: function (e) {
e.container.kendoWindow("title", "Alterar Centro de Custo");
}
});
function gridDataBound() {
$("#grid tbody tr .btn-successo").each(function () {
var currentDataItem = $("#grid").data("kendoGrid").dataItem($(this).closest("tr"));
//Check in the current dataItem if the row is editable
if (currentDataItem.Status == "Ativo") {
$(this).remove();
}
})
$("#grid tbody tr .btn-excluir").each(function () {
var currentDataItem = $("#grid").data("kendoGrid").dataItem($(this).closest("tr"));
//Check in the current dataItem if the row is editable
if (currentDataItem.Status == "Inativo") {
$(this).remove();
}
})
$("#grid tbody tr .btn-alterar").each(function () {
var currentDataItem = $("#grid").data("kendoGrid").dataItem($(this).closest("tr"));
//Check in the current dataItem if the row is editable
if (currentDataItem.Status == "Inativo") {
$(this).remove();
}
})
if ($('#canEdit').val().toUpperCase() == "FALSE") {
$('#grid').find(".btn-alterar").hide();
$('#grid').find(".btn-successo").hide();
$('#grid').find(".btn-excluir").hide();
}
}
What happens is that when I get an error, the error message inside complete on update event is shown, but when the update succeed the instruction $("#grid").data("kendoGrid").dataSource.read() is not being called.
I would like to know if there's another way to do that, like save using $.ajax or if there's another event to call after "Update Success".
-----------------------------------------------------------------
UPDATE
I changed the 'data' to 'e' in the complete method under update and it's working now.

Related

Bind search results in kendoGrid MVC

I need help here.I have kendogrid, which need to have a popup.Popup is loading from template(view1.cshtml) and everything is working perfectly.But when i add search in my page, and than add following code
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("ListFinances", "Jobs"))",
type: "POST",
dataType: "json",
data: additionalData
},
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
in rest of the code in grid(search results are bind here to grid),search is working, popup is not working nothing and is showing when i click on the button to show up popup.What is here wrong?Thanks
<script>
$(function() {
$("#jobs-grid").kendoGrid({
dataSource: {
data: #Html.Raw(JsonConvert.SerializeObject(Model.FinishedJobs)),
schema: {
model: {
fields: {
JobNumber: { type: "string" },
CustomerId: { type: "number" },
JobCount: { type: "number" },
JobYear: { type: "number" },
Status: { type: "number" },
Position: { type: "number" },
Finished: { type: "boolean" },
HasInvoice: { type: "boolean" },
}
}
},
#*type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("ListFinances", "Jobs"))",
type: "POST",
dataType: "json",
data: additionalData
},
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},*#
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
},
//dataBound: onDataBound,
columns: [
#*{
field: "Status",
title: "#T("gp.Jobs.Fields.Status")",
template: '#= Status #'
},*#
{
field: "JobNumber",
title: "#T("gp.Job.Fields.JobNumber")",
template: '#= JobNumber #'
},
{
field: "CustomerId",
title: "#T("gp.Job.Fields.Customer")",
template: '#= Customer.Name #'
},
{
field: "Id",
title: "#T("gp.Job.Fields.Name")"
},
#*{
field: "ShortDesc",
title: "#T("gp.Jobs.Fields.ShortDesc")"
},*#
{
field: "DateCompletition",
title: "#T("gp.Job.Fields.DateCompletition")"
},
{
field: "Id",
title: "#T("Common.Edit")",
width: 130,
template: '#T("Common.Edit")'
}
],
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50]
},
editable: {
confirmation: false,
mode: "inline"
},
scrollable: false,
// sortable: true,
// navigatable: true,
// filterable: true,
// scrollable: true,
selectable: true,
rowTemplate: kendo.template($("#jobRowTemplate").html()),
});
</script>

How do I add phone number & email validation to Kendo-UI Grid?

Given the grid supplied in the code below, how do I set validation on the phone and email to take advantage of the validation and masked input features kendo provides on this page (http://demos.telerik.com/kendo-ui/maskedtextbox/index)?
For example, if the user types in 5628103322, it should format it as (562)810-3322 as the demo on their page shows. Also if a number that was not entered correctly it should provide an error message.
Same for email, how do we do this?
<div id="grid"></div>
<script>
var crudServiceBaseUrl = "/api",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/companies",
dataType: "json",
type: "POST"
},
update: {
url: crudServiceBaseUrl + "/companies/update",
dataType: "json",
type: "POST"
},
destroy: {
url: crudServiceBaseUrl + "/companies/destroy",
dataType: "json",
type: "POST"
},
create: {
url: crudServiceBaseUrl + "/companies/create",
dataType: "json",
type: "POST"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
error: function (e) {
/* the e event argument will represent the following object:
{
errorThrown: "Unauthorized",
sender: {... the Kendo UI DataSource instance ...}
status: "error"
xhr: {... the Ajax request object ...}
}
*/
//alert("Status: " + e.status + "; Error message: " + e.errorThrown);
console.log("Status: " + e.status + "; Error message: " + e.errorThrown);
},
autoSync: false,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
pageSize: 20,
selectable: "multiple cell",
allowCopy: true,
columnResizeHandleWidth: 6,
schema: {
total: "itemCount",
data: "items",
model: {
id: "id",
fields: {
id: { editable: false, nullable: true },
name: { validation: { required: true } },
phone: { type: "string" },
email: { type: "string" }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
height: 550,
groupable: true,
sortable: {
mode: "multiple",
allowUnsort: true
},
toolbar: ["create"],
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
reorderable: true,
resizable: true,
columnMenu: true,
filterable: true,
columns: [
{ field: "name", title: "Company Name" },
{ field: "phone", title:"Phone" },
{ field: "email", title:"Email" },
{ command: ["edit", "destroy"], title: "Operations", width: "240px" }
],
editable: "popup"
});
</script>
UPDATE::
$("#grid").kendoGrid({
dataSource: dataSource,
groupable: true,
sortable: {
mode: "multiple",
allowUnsort: true
},
toolbar: ["create"],
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
reorderable: true,
resizable: true,
columnMenu: true,
filterable: true,
columns: [
{ field: "name", title: "Company Name" },
{
field: "phone",
title: "Phone",
editor: function(container, options){
var input = $('<input type="tel" data-tel-msg="Invalid Phone Number!" class="k-textbox"/>');
input.attr("name", options.field);
input.kendoMaskedTextBox({
mask: "(999) 000-0000"
});
input.appendTo(container);
}
},
{
field: "email",
title: "Email",
editor: function(container, options){
var input = $('<input type="email" data-email-msg="Invalid email!" class="k-textbox"/>');
input.attr("name", options.field);
input.appendTo(container);
}
},
{ command: ["edit", "destroy"], title: "Operations", width: "240px" }
],
editable: "popup"
});
the grid code above has changed, it almost works perfectly now thanks to the answer below, now I just need to figure out how to add validation to the phone number and email fields so input is required, and correct input.
UPDATE #2
The code below now works perfectly thanks to the answer, just wanted to share it to others that might need help. Something interesting to note is the model rule phonerule has to be named whatever the text in the middle between the dashes of this is data-phonerule-msg. I'm guessing Kendo-UI must look for that when looking for custom rules.
<div id="grid" style="height:100%;"></div>
<script>
$(window).on("resize", function() {
kendo.resize($("#grid"));
});
var crudServiceBaseUrl = "/api",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/companies",
dataType: "json",
type: "POST"
},
update: {
url: crudServiceBaseUrl + "/companies/update",
dataType: "json",
type: "POST"
},
destroy: {
url: crudServiceBaseUrl + "/companies/destroy",
dataType: "json",
type: "POST"
},
create: {
url: crudServiceBaseUrl + "/companies/create",
dataType: "json",
type: "POST"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
error: function (e) {
/* the e event argument will represent the following object:
{
errorThrown: "Unauthorized",
sender: {... the Kendo UI DataSource instance ...}
status: "error"
xhr: {... the Ajax request object ...}
}
*/
//alert("Status: " + e.status + "; Error message: " + e.errorThrown);
console.log("Status: " + e.status + "; Error message: " + e.errorThrown);
},
autoSync: false,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
pageSize: 20,
selectable: "multiple cell",
allowCopy: true,
columnResizeHandleWidth: 6,
schema: {
total: "itemCount",
data: "items",
model: {
id: "id",
fields: {
id: { editable: false, nullable: true },
name: { validation: { required: true } },
phone: {
type: "string",
validation: {
required: true,
phonerule: function(e){
if (e.is("[data-phonerule-msg]"))
{
var input = e.data('kendoMaskedTextBox');
//If we reached the end of input then it will return -1 which means true, validation passed
//Otherwise it won't === -1 and return false meaning all the characters were not entered.
return input.value().indexOf(input.options.promptChar) === -1;
}
return true; //return true for anything else that is not data-phonerule-msg
}
}
},
email: { type: "string", validation: { required: true, email:true } }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
groupable: true,
sortable: {
mode: "multiple",
allowUnsort: true
},
toolbar: ["create"],
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
reorderable: true,
resizable: true,
columnMenu: true,
filterable: true,
columns: [
{ field: "name", title: "Company Name" },
{
field: "phone",
title: "Phone",
editor: function(container, options){
//pattern="[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}"
var input = $('<input type="tel" data-phonerule-msg="Invalid Phone Number!" class="k-textbox" required />');
input.attr("name", options.field);
input.kendoMaskedTextBox({
mask: "(999) 000-0000"
});
input.appendTo(container);
}
},
{
field: "email",
title: "Email",
editor: function(container, options){
var input = $('<input type="email" data-email-msg="Invalid email!" class="k-textbox" required/>');
input.attr("name", options.field);
input.appendTo(container);
}
},
{ command: ["edit", "destroy"], title: "Operations", width: "240px" }
],
editable: "popup"
});
</script>
You should add to column definition custom editor with validation attributes:
{
field: "email",
title:"Email",
editor: function(container, options) {
var input = $('<input type="email" data-email-msg="Invalid email!" class="k-textbox"/>');
input.attr("name", options.field);
input.appendTo(container);
}
}
Update: phone validation:
add this attribute to phone input ("phonerule" - is the name of custom validation rule):
data-phonerule-msg="Invalid phone!"
add custom validation rule to schema.model.fields.phone:
phone: {
type: "string",
validation: {
phonerule: function(e) {
if (e.is("[data-phonerule-msg]"))
{
var input = e.data('kendoMaskedTextBox');
return input.value().indexOf(input.options.promptChar) === -1;
}
return true;
}
}
}
You can use this code to add mobile and email validation -
schema: {
model: {
id: "id",
fields: {
mobile: {
editable: true, validation: {
required: true,
Mobilevalidation: function (input) {
if (input.is("[name='mobile']")) {
if ((input.val()) == "") {
input.attr("data-Mobilevalidation-msg", "Mobile number required");
return /^[A-Z]/.test(input.val());
}
else {
if (/^\d+$/.test(input.val())) {
if (input.val().length == 10) {
return true;
} else {
input.attr("data-Mobilevalidation-msg", "Mobile number is invalid");
return /^[A-Z]/.test(input.val());
}
}
else {
input.attr("data-Mobilevalidation-msg", "Mobile number is invalid");
//alert(/^[A-Z]/.test(input.val()));
return /^[A-Z]/.test(input.val());
}
return true;
}
}
return true;
}
}
},
email: { editable: true, type: "email", validation: { required: true } },
}
}
}

Kendo Grids Hierarchy Adding New Row - Pass Parent ID to New Child Record

I am new to kendo and javascript so excuse any lapses in knowledge... Below I have a basic kendo hierarchical grid. When I try to add a new record to the child grid, the record gets added via a post method in my controller but the parent reference ID doesn't get passed correctly and instead 0 gets passed as the foreign key reference to the child table.
Here is my Parent Grid
//-----------------KENDO GRID DATA-----------------
var datasource = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
//url: sBaseUrl,
url: baseUrl + "StationLogPaperTicketOdata",
type: "get",
dataType: "json",
contentType: "application/json"
},
update: {
type: "PUT",
url: function (data) {
return baseUrl + "StationLogPaperTicketOdata(" + data.log_id + ")";
},
dataType: "json",
},
//parameterMap: function(options, operation) {
// if (operation !== "read" && options.models) {
// return {models: kendo.stringify(options.models)};
// }
//}
},
schema: {
data: "value",
total: function (data) {
return data['odata.count'];
},
model: {
id: "log_id",
fields: {
log_id: { type: "number" },
log_station: { type: "string" },
log_sourceCode: { type: "string", nullable: true },
log_carrierName: { type: "string", nullable: true },
log_ticketNumber: { type: "string", nullable: true },
log_deliveryTS: { type: "date" },
log_leaseNumber: { type: "string", nullable: true },
log_leaseName: { type: "string", nullable: true },
log_type: { type: "string" },
log_rackNumber: { type: "number", nullable: true },
log_logNumber: { type: "number", nullable: true },
log_driverFirstName: { type: "string", nullable: true },
log_driverLastName: { type: "string", nullable: true },
log_linkedTicketNumber: { type: "string", nullable: true },
log_volumeGross: { type: "number" },
log_volumeNet: { type: "number", nullable: true },
log_originalDestination: { type: "string", nullable: true },
log_lastModifiedTS: { type: "date", editable: false },
log_lastModifiedBy: { type: "string", editable: false },
log_meterReadOpen: { type: "number", nullable: true },
log_volumeNetCalculated: { type: "number", nullable: true },
log_isDeleted: { type: "string", nullable: true },
log_detailIsDeleted: { type: "string", nullable: true },
log_paperTicketIsApproved: { type: "string", nullable: true, editable: false },
log_accountingDate: { type: "date", nullable: true },
log_stationNumber: { type: "string", nullable: true },
log_isPickup: { type: "string", nullable: true },
log_operatorNumber: { type: "string", nullable: true },
log_controlNumber: { type: "string", nullable: true },
log_dispatchConfirmationNumber: { type: "string", nullable: true },
log_groupId: { type: "number", nullable: true },
log_groupSource: { type: "string", nullable: true },
log_isTank: { type: "string", nullable: true },
log_meterReadClose: { type: "number", nullable: true },
log_obsTemperature: { type: "number", nullable: true },
log_tankTemperature: { type: "number", nullable: true },
log_obsGravity: { type: "number", nullable: true },
log_bswPercent: { type: "number", nullable: true },
log_gaugeBeforeUnloadFeet: { type: "number", nullable: true },
log_gaugeBeforeUnloadInches: { type: "number", nullable: true },
log_gaugeBeforeUnloadQuarter: { type: "number", nullable: true },
log_comments: { type: "string", nullable: true }
}
}
},
pageSize: 50,
serverPaging: true,
serverfilering: true,
serverSorting: true,
sort: { field: "log_id", dir: "asc" },
});
//-----------------KENDO GRID-----------------
$("#grid").kendoGrid({
dataSource: datasource,
pageable:
{
refresh: true,
pageSizes: [10,25,50,100],
buttonCount: 5
},
height: 600,
width: 500,
sortable: true,
scrollable: true,
reorderable: true,
toolbar: ["save", "cancel"],
editable: true,
filterable: {
mode: "row"
},
selectable: "row",
resizable: true,
detailInit: detailInit,
dataBound: onDataBound,
columns: [
//{ field: "log_id", title: "ID", width: 130 }, //THIS IS FOR TESTING PURPOSES
{
field: "log_paperTicketIsApproved",
title: "Approved",
width: 130,
template:
"# if(log_paperTicketIsApproved == 'Y') { #" +
"# approved = true #" +
"# } else { #" +
"# approved = false #" +
"# } #" +
"<input name='paperTicketIsApproved' class='check_row' type='checkbox' data-bind='checked: approved' #= approved ? checked='checked' : '' #/>"
},
{ field: "log_type", title: "Source", width: 130 },
{ field: "log_rackNumber", title: "Connect Point (LACT)", width: 150 },
{ field: "log_sourceCode", title: "Carrier Source Code", width: 140 },
{ field: "log_carrierName", title: "Carrier Name", width: 130 },
{ field: "log_ticketNumber", title: "Ticket Number", width: 130 },
{ field: "log_deliveryTS", title: "Date", width: 160, format: "{0:MM-dd-yyyy}" },
{ field: "log_deliveryTS", title: "Time", width: 140, format: "{0:hh:mm tt}" },
{ field: "log_volumeGross", title: "Gross BBLs", width: 140 },
{ field: "log_volumeNet", title: "Net BBLs", width: 140 },
{ field: "log_leaseName", title: "Lease Name", width: 200 },
{ field: "log_driverFirstName", title: "Driver First Name", width: 160 }, // template: "#= log_driverFirstName # #=log_driverLastName #" },
{ field: "log_driverLastName", title: "Driver Last Name", width: 160 },
{ field: "log_bswPercent", title: "Obs. BS&W %", width: 140 },
{ field: "log_obsGravity", title: "Obs. Gravity", width: 130 },
{ field: "log_obsTemperature", title: "Obs. Temperature", width: 150 },
{ field: "log_linkedTicketNumber", title: "Linked Ticket Number", width: 150 },
{ field: "log_originalDestination", title: "Original Destination", width: 150 },
{ field: "log_lastModifiedBy", title: "Last Modified By", width: 170 },
{ field: "log_lastModifiedTS", title: "Last Modified Date", width: 170, format: "{0:MM-dd-yyyy hh:mm tt}" },
//{ field: "log_station", title: "Station", width: 140 } //THIS IS FOR TESTING PURPOSES ONLY
]
});
var grid = $("#grid").data("kendoGrid");
//grid.bind("dataBound", onDataBound);
grid.table.on("click", ".check_row", selectRow)
}
and here is the Child Grid
//-----------------KENDO CHILD-GRID DATA-----------------
function detailInit(e) {
var datasource = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
url: baseUrl + "StationLogComments",
type: "get",
dataType: "json"
},
update: {
type: "put",
url: function (data) {
return baseUrl + "StationLogComments(" + data.log_commentID + ")";
},
dataType: "json",
contentType: "application/json"
},
create: {
url: baseUrl + "StationLogComments",
type: "post",
dataType: "json"
},
},
schema: {
data: "value",
total: function (data) {
return data['odata.count'];
},
model: {
id: "log_commentID",
fields: {
log_commentID: { type: "number" },
log_id: { type: "number" },
log_comment: { type: "string" },
log_commentCreatedBy: { type: "string" },
log_commentCreatedDate: { type: "date", editable: false }
}
}
},
serverPaging: true,
serverSorting: true,
sort: { field: "log_commentCreatedDate", dir: "asc" },
serverFiltering: true,
width: 100,
pageSize: 10,
filter: { field: "log_id", operator: "eq", value: e.data.log_id }
});
//-----------------KENDO CHILD-GRID-----------------
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: datasource,
scrollable: false,
toolbar: ["create", "save", "cancel"],
saveChanges: function (e) {
debugger;
},
editable: true,
resizable: true,
width: 600,
//sortable: true,
//pageable: true,
columns: [
{ field: "log_id", title: "log_id", width: "100px" },
{ field: "log_comment", title: "Comment", width: "500px" },
{ field: "log_commentCreatedBy", title: "Created By", width: "100px" },
{ field: "log_commentCreatedDate", title: "Created Date", format: "{0:MM-dd-yyyy hh:mm tt}" }
]
});
}
What can I put in saveChanges: to get my desired result? Thanks
RESOLVED!!
I found my own answer and am posting it here in the hopes that it may help someone else..
In the model of my Child Grid I add this line of code to the foreign key reference:
defaultValue: e.data.log_id
so now my child grid model looks like this
model: {
id: "log_commentID",
fields: {
log_commentID: { type: "number" },
log_id: { type: "number", defaultValue: e.data.log_id },
log_comment: { type: "string" },
log_commentCreatedBy: { type: "string" },
log_commentCreatedDate: { type: "date", editable: false }
}

Kendo UI grid not triggering transport create URL

Ive a kendoUI grid doing CRUD from a web service. For some reason, read command works perfectly and populates my grid.
But when I try to create a new record, despite that it shows the new record in the grid and i can edit its fields, button save does not trigger the web service.
Checking out http logs, I see no hit on the service. Only on "read".
This is the grid's code:
$(function() {
$("#grid").kendoGrid({
dataSource: {
transport: {
read: "libyMsg.php?way=getUsrMsgList"
},
create: {
url: "libyMsg.php?way=createMsg",
type: "PUT"
},
update: {
url: "libyMsg.php?way=updateeMsg",
type: "PUT"
},destroy: {
url: "libyMsg.php?way=destroyMsg",
type: "PUT"
},
batch: true,
pageSize: 10,
schema: {
data: "data",
model: {
id: "msg_id",
fields: {
msg_id: { editable: false, nullable: true },
msg_title: { validation: { required: true } },
msg_content: { validation: { required: true } },
msg_type: { type: "number", validation: { min: 0, required: true }},
msg_date: { type: "date", validation: { required: true } },
msg_status: { type: "number", validation: { min: 0, required: true } }
}
}
},
},
columns: [{ field: "msg_id", width: 40,title: "ID" },
{ field: "msg_title",width: 300, title: "Title" },
{ field: "msg_content", width: 300,title: "Content" },
{ field: "msg_type", width: 40,title: "Type" },
{ field: "msg_date", width: 300,title: "Date" },
{ field: "msg_status", width: 40,title: "Status" }],
scrollable: true,
sortable: true,
editable:true,
pageable: {
refresh: true,
pageSizes: true
},
toolbar: ["create", "save", "cancel"],
});
});
This is driving me crazy. Anyone?
Ty/M
Your transport is wrong. Try this instead:
transport:{
read :"libyMsg.php?way=getUsrMsgList",
create :{
url :"libyMsg.php?way=createMsg",
type:"PUT"
},
update :{
url :"libyMsg.php?way=updateeMsg",
type:"PUT"
},
destroy:{
url :"libyMsg.php?way=destroyMsg",
type:"PUT"
}
},
create, update and destroy should be part of transport.

Is it possible to have full CRUD functions in kendo grid with local data

I'm currently implementing a kendo grid and i'm populating it with local data.
That is; I have generated a JSON string from my action and supplying that string on the view page.
In the end i would like to know if it is possible to implement full CRUD functions with local data?
here's a sample of the code written so far;
<div id="example" class="k-content">
<div id="grid"></div>
<script>
$(document).ready(function() {
var myData = ${coursemodules},
dataSource = new kendo.data.DataSource({
data: myData,
batch: true,
pageSize: 30,
schema: {
model: {
id: "id",
fields: {
id: { editable: false, nullable: true},
name: { type: "string", validation: { required: true }},
qualificationLevel: { type: "string", validation: { required: true }},
description: { type: "string", validation: { required: true }},
published: { type: "boolean" },
gateApprove: { type: "boolean" },
duration: { type: "number", validation: { min: 1, required: true } },
academicBody: { type: "string" }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
height: 350,
scrollable: true,
sortable: true,
pageable: true,
toolbar: ["create", "save", "cancel"],
columns: [
{
field: "id",
title: "ID",
width: '3%'
},
{
field: "name",
title: "Course Title",
width: '20%'
},
{
field: "description",
title:"Description",
width: '35%'
},
{
field: "published",
title: "Published",
width: '7%'
},
{
field: "gateApprove",
title: "Gate Approve",
width: '7%'
},
{
field: "duration",
title: "Duration",
width: '5%'
},
{
field: "academicBody.shortName",
title: "Academic Body",
width: '10%'
}
],
editable: true
});
});
</script>
</div>
I have realise that for the datasource, you have to declare transport to implement the CRUD. However, I need to declare "data". I tried declaring both transport and data. That doesn't seem to work.
Yes you can Here is JSFiddle Hope this will help you.
// this should be updated when new entries are added, updated or deleted
var data =
[{
"ID": 3,
"TopMenuId": 2,
"Title": "Cashier",
"Link": "www.fake123.com"},
{
"ID": 4,
"TopMenuId": 2,
"Title": "Deposit",
"Link": "www.fake123.com"}
];
$("#grid").kendoGrid({
dataSource: {
transport: {
read: function(options) {
options.success(data);
},
create: function(options) {
alert(data.length);
},
update: function(options) {
alert("Update");
},
destroy: function(options) {
alert("Destroy");
alert(data.length);
}
},
batch: true,
pageSize: 4,
schema: {
model: {
id: "ID",
fields: {
ID: {
editable: false,
nullable: true
},
TopMenuId: {
editable: false,
nullable: true
},
Title: {
editable: true,
validation: {
required: true
}
},
Link: {
editable: true
}
}
},
data: "",
total: function(result) {
result = result.data || result;
return result.length || 0;
}
}
},
editable: true,
toolbar: ["create", "save", "cancel"],
height: 250,
scrollable: true,
sortable: true,
filterable: false,
pageable: true,
columns: [
{
field: "TopMenuId",
title: "Menu Id"},
{
field: "Title",
title: "Title"},
{
field: "Link",
title: "Link"},
{
command: "destroy"}
]
});
When binding local data, the Grid widget utilizes an abstraction that represents a local transport. Therefore, it does not require a custom transport; modifications made in the grid are reflected to the bound data source. This includes rollbacks through a cancellation.
There is fully functional example of this in telerik documentation
What you need is define transport block in dataSource object with custom CRUD funtions which update local source.
transport: {
create: function(options){
var localData = JSON.parse(localStorage["grid_data"]);
options.data.ID = localData[localData.length-1].ID + 1;
localData.push(options.data);
localStorage["grid_data"] = JSON.stringify(localData);
options.success(options.data);
},
read: function(options){
var localData = JSON.parse(localStorage["grid_data"]);
options.success(localData);
},
update: function(options){
var localData = JSON.parse(localStorage["grid_data"]);
for(var i=0; i<localData.length; i++){
if(localData[i].ID == options.data.ID){
localData[i].Value = options.data.Value;
}
}
localStorage["grid_data"] = JSON.stringify(localData);
options.success(options.data);
},
destroy: function(options){
var localData = JSON.parse(localStorage["grid_data"]);
for(var i=0; i<localData.length; i++){
if(localData[i].ID === options.data.ID){
localData.splice(i,1);
break;
}
}
localStorage["grid_data"] = JSON.stringify(localData);
options.success(localData);
},
}

Categories

Resources