Related
I Set Kendo Ui Grid and footer,
footer will get total price,
but it always can't get last data.
hope somebody can help to fix it.
and i try $("#Grid").data("kendoGrid").refresh();
but it didn't work for me.
kendoui grid set
dataSource
var AddGriddataSource = new kendo.data.DataSource({
data: [],
schema: {
model: {
fields: {
id: 'No',
Name: { editable: false, nullable: false },
txtStockNum: { editable: false, nullable: false },
txtReturnNum: { editable: true, nullable: false },
txtPricetax: { editable: false, nullable: false },
txtPriceNum1: { editable: false, nullable: false }
}
} // end of model
}, // end of schema
aggregate: [{ field: "txtPriceNum", aggregate: "sum" }, { field: "txtPriceNum1", aggregate: "sum" }],
});
Cell
var AddGridCells = [
{ field: "Name", title: "Name", width: "20px" },
{ field: "StockNum", title: "Stock", width: "20px" },
{ field: "txtReturnNum", title: "txtReturnNum", width: "100px", template: '<input id = "Del" class="returnDel" type="button" value="▼" style="margin: -1px" /><input id="Txt_test1" class="returnTxtBox" type="textbox" value= #=txtReturnNum# style="margin: 2px" /><input id = "plus" class="returnPlus" type="button" value="▲" style="margin: -1px" />' },
{ field: "txtPrice", title: "txtPrice", width: "20px", hidden: true },
{ field: "txtPricetax", title: "txtPricetax", width: "20px", format: "{0:n3}" },
{ field: "txtPriceNum", title: "Total", width: "20px", footerTemplate: "#= kendo.toString(sum, '0.000')#", hidden: true },
{ field: "txtPriceNum1", title: "Total", width: "30px", footerTemplate: "<span id='footerPlaceholder'>#= kendo.toString(sum, '0.000')#</span>", format: "{0:n3}" },
{ command: [{ text: "X", click: DelchooseDetails }], title: " ", width: "10px" },
];
and
$("#AddGrid").kendoGrid({
dataSource: AddGriddataSource,
selectable: "row",
scrollable: false,
columns: AddGridCells,
change: numberInput,
pageable: {
buttonCount: 3,
messages: GridPageMsg
},
height: '100%',
editable: true
}).data("kendoGrid");
JQuery todo
$(document).on('click', '.returnPlus', function (e) {
if (nowStatus != 0) {
return;
}
var ds2 = $("#AddGrid").data("kendoGrid").dataSource;
var row = $(this).closest("tr"),
grid = $("#AddGrid").data("kendoGrid"),
dataItem = grid.dataItem(row);
debugger;
ds2.fetch(function () {
dataItem.txtReturnNum = dataItem.txtReturnNum - (-1);
dataItem.txtPriceNum = dataItem.txtReturnNum * dataItem.txtPrice;
dataItem.txtPriceNum1 = mulFloat(dataItem.txtReturnNum, dataItem.txtPricetax);
})
$("#AddGrid").data("kendoGrid").refresh();
return;
});
$(document).on('click', '.returnDel', function (e) {
if (nowStatus != 0) {
return;
}
var ds2 = $("#AddGrid").data("kendoGrid").dataSource;
var row = $(this).closest("tr"),
grid = $("#AddGrid").data("kendoGrid"),
dataItem = grid.dataItem(row);
debugger;
ds2.fetch(function () {
dataItem.txtReturnNum = dataItem.txtReturnNum - (1);
dataItem.txtPriceNum = dataItem.txtReturnNum * dataItem.txtPrice;
dataItem.txtPriceNum1 = mulFloat(dataItem.txtReturnNum, dataItem.txtPricetax);
})
$("#AddGrid").data("kendoGrid").refresh();
return;
});
I'm not sure If i does not described correctly,so i record video
https://imgur.com/mePv5qI
How can i do will be correct
Why are you using fetch()? It seems that you don't need it, since you're not updating data from api. You're only updating local data, right ? So remove it and change dataItem directly:
var row = $(this).closest("tr"),
grid = $("#AddGrid").data("kendoGrid"),
dataItem = grid.dataItem(row);
dataItem.txtReturnNum = dataItem.txtReturnNum - (-1);
dataItem.txtPriceNum = dataItem.txtReturnNum * dataItem.txtPrice;
dataItem.txtPriceNum1 = mulFloat(dataItem.txtReturnNum, dataItem.txtPricetax);
$("#AddGrid").data("kendoGrid").refresh();
Or
var row = $(this).closest("tr"),
grid = $("#AddGrid").data("kendoGrid"),
dataItem = grid.dataItem(row);
dataItem.set('txtReturnNum', dataItem.txtReturnNum - (-1));
dataItem.set('txtPriceNum', dataItem.txtReturnNum * dataItem.txtPrice);
dataItem.set('txtPriceNum1', mulFloat(dataItem.txtReturnNum, dataItem.txtPricetax));
I am currently making some modifications on an application developed by someone else. The application uses the KendUI to render data on a grid. By default, the assumption would have been that the grid should be able to do filters and sort. When I turned the grid filters on and chose specific fields to filter by, I get status 500 error;
GET http://localhost/RFG/Workpermits?take=10&skip=0&page=1&pageSize=10&filter%5Blogic%5D=and&filter%5Bfilters%5D%5B0%5D%5Bfield%5D=Id&filter%5Bfilters%5D%5B0%5D%5Boperator%5D=eq&filter%5Bfilters%5D%5B0%5D%5Bvalue%5D=7&filter%5Bfilters%5D%5B1%5D%5Bfield%5D=ContractorName&filter%5Bfilters%5D%5B1%5D%5Boperator%5D=contains&filter%5Bfilters%5D%5B1%5D%5Bvalue%5D=Sor 500 (Internal Server Error)
Here is the piece of codes being used.
var workPermitsListView = new WorkPermitsListView();
$(document).ready(function () {
workPermitsListView.initializeControls();
var kgrid = $("#workPermitsGrid").data("kendoGrid");
var oldOptions = kgrid.getOptions();
var options = localStorage["kendo-grid-options"];
if (options) {
var savedOptions = JSON.parse(options);
var editFunc = oldOptions.columns[0];
savedOptions.columns[0] = editFunc;
kgrid.setOptions(savedOptions);
kgrid.dataSource.read();
}
});
function WorkPermitsListView() {
this.initializeControls = function () {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1);
if (url == "refresh=true") {
window.location = window.location;
window.location = "WorkPermitsList.aspx";
} else if (url == "refresh=false") {
window.location = window.location;
}
$("#addWorkPermitBtn").on("click", function (e) { e.preventDefault(); workPermitsListView.createNewWorkPermit(); });
$("#omniSearchAdvTxt").keypress(function (e) { if (e.keyCode === 13) { $("#advSearchWorkPermitBtn").click(); } });
$("#omniSearchWorkPermitID").keypress(function (e) { if (e.keyCode === 13) { $("#advSearchWorkPermitBtn").click(); } });
$("#omniSearchLocation").keypress(function (e) { if (e.keyCode === 13) { $("#advSearchWorkPermitBtn").click(); } });
// $("#addWorkPermitBtn").kendoButton().data("kendoButton").enable(secScriptObj.canWriteWorkPermit);
if (!secScriptObj.canWriteWorkPermit) {
$("#addWorkPermitBtn").hide();
}
else {
$("#addWorkPermitBtn").kendoButton().data("kendoButton").visible = true;
$("#addWorkPermitBtn").kendoButton().data("kendoButton").enable(secScriptObj.canWriteWorkPermit);
}
var gridDefaultActionName = secScriptObj.canWriteWorkPermit ? "Edit" : "View";
var gridDataSource = new kendo.data.DataSource(
{
transport: { read: PTWApp.getSitePrefix() + "/Workpermits" },
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
schema: {
total: "total",
data: "data",
model: {
id: "Id"
}
}
}
);
//var options = localStorage["grid-options"];
$("#workPermitsGrid").kendoGrid({
autoBind: false,
dataSource: gridDataSource,
scrollable: true,
sortable: true,
dataBound: WorkPermitsListView.onDataBind,
pageable: {
input: true,
numeric: false
},
noRecords: { template: "<div class='noRecordsDiv'>No permits to display. Use search for more or contact the administrator for assistance.</div>" },
filterable: true,
schema:{
model:{
fields:{
Id:{type:"int"},
StartDate:{type:"date"},
EndDate:{type:"date"}
}
}
},
columns: [
{
command: {
click: WorkPermitsListView.editWorkPermit,
name: "modify",
text: gridDefaultActionName
},
width: "70px"
},
{
field: "Id",
title: "Permit #",
width: "7%" ,
headerAttributes: { style: "white-space: normal"}
},
{
field: "Status",
title: "Status",
template: "#= WorkPermitsListView.addStatusImg(data)#",
width: "7%",
filterable:false,
headerAttributes: { style: "white-space: normal"},
editor: workPermitsListView.selectPermit
},
{
field: "StartDate",
title: "Start Date",
template: "#= PTWApp.ConvertDate(data.StartDate)#",
width: "7.5%",
filterable:false,
headerAttributes: { style: "white-space: normal"}
},
{
field: "EndDate",
title: "End Date",
template: "#= PTWApp.ConvertDate(data.EndDate)#",
width: "7.5%",
filterable:false,
format:"{0:MMM dd yyyy}",
headerAttributes: { style: "white-space: normal"}
},
{
field: "ContractorName",
title: "Contractor",
width: "8.5%",
headerAttributes: { style: "white-space: normal"}
},
{
field: "ContractorSupervisorName",
title: "Supervisor",
width: "8.5%",
filterable:false,
headerAttributes: { style: "white-space: normal"}
},
{
field: "ContractorSupervisorPhone",
title: "Phone #",
template: "#: WorkPermitsListView.formatPhone(ContractorSupervisorPhone) #",
width: "7.5%",
filterable:false,
headerAttributes: { style: "white-space: normal"}
},
{
field: "RequestedBy",
title: "Requester",
width: "7.5%",
filterable:false
},
{
field: "Attachments",
title: "Files",
template: "#= WorkPermitsListView.addFileImg(data)#",
filterable:false,
width: "6%"
},
{
field: "IsEvent",
title: "Events",
template: "#= WorkPermitsListView.addEventImg(data)#",
width: "5.5%"
},
{
field: "Description",
title: "Work Description",
width: "33.5%"
//, attributes: { "class": "shortText" } }
}
]
});
/** var grid = $("#workPermitsGrid").data("kendoGrid");
var selected = {};
if (options) {
workPermitsGrid.setOptions(JSON.parse(options));
}
windows.onbeforeunload = function () {
localStorage["grid-options"] = kendo.stringify(workPermitsGrid.getOptions());
return;
}
var grid = $("#workPermitsGrid").data("kendoGrid");
var selected = {};
var gridOptions = localStorage["kg-options"];
console.log(gridOptions);
if (gridOptions) {
grid.setOptions(JSON.parse(gridOptions));
}
else {
localStorage["kg-options"] = kendo.stringify(grid.getOptions());
}
**/
// attaches the tool tip to the cells
$(".shortText").kendoTooltip({
content: function (e) {
var target = e.target; // the element for which the tooltip is shown
return target.text(); // set the element text as content of the tooltip
}
});
gridDataSource.bind("error", function (error) { if (error.errors != undefined && error.errors.length > 0) { alertBox("Error:" + error.errors[0].error); } else { alertBox("Error fetching data: " + error.status); } });
$("#advSearchWorkPermitBtn").on("click", function () {
workPermitsListView.searchWorkPermit($("#omniSearchAdvTxt").val(), $("#omniSearchWorkPermitID").val(), $("#omniSearchContractor").val(), $("#workPermitStatusDropDown").val());
workPermitsListView.advancedSearchWindow.data("kendoWindow").close();
});
$(window).on("omniSearchTriggered", function (event, searchText) { workPermitsListView.searchWorkPermit(searchText, "", "", ""); });
$(window).on("AdvancedSearchClicked", function (event, searchText) { workPermitsListView.showAdvancedSearch(); });
if (this.getParameterValue('advsearch') === 'true') {
this.showAdvancedSearch();
}
else if (this.getParameterValue('omnisearch') !== undefined) {
searchText = this.getParameterValue('omnisearch')
$("#omniSearchTextBox").val(searchText);
this.searchWorkPermit(searchText, "", "", "");
}
else {
var grid = $("#workPermitsGrid").data("kendoGrid");
grid.dataSource.read();
}
}
WorkPermitsListView.formatPhone = function (phone)
{
return phone.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
}
/** Redirects the browser to the work permit edit page
*
* #param sender object reference to the kendo grid
* #returns nothing
*/
WorkPermitsListView.editWorkPermit = function (e) {
e.preventDefault();
var data = this.dataItem($(e.currentTarget).closest("tr"));
window.location = 'WorkPermit.aspx?pid=' + data.Id;
}
/** Returns a status image
*
* #param model object reference to the work permit model
* #returns Html with img tag set to the right status image
*/
WorkPermitsListView.addStatusImg = function (model) {
if (model.Status === 2) {
return '<img src="../img/open_wp_status.png" class="statusIcon"/> In Progress';
}
else if (model.Status === 3) {
return '<img src="../img/closed_wp_status.png" class="statusIcon"/> Rejected';
}
else if (model.Status === 4) {
return '<img src="../img/cancelled_wp_status.png" class="statusIcon"/> Cancelled';
}
else if (model.Status === 5 ) {
return '<img src="../img/expired_wp_status.png" class="statusIcon"/> Expired';
}
if (model.Status === 6) {
return '<img src="../img/approved_wp_status.png" class="statusIcon"/> Approved';
}
}
/**
Get file attachment and display attachement icon
**/
WorkPermitsListView.addFileImg = function (model) {
var permitId = model.Id
return '<a href><img id="permitFile" src="../img/permit-attachment-icon.jpg" class="statusIcon" onclick="WorkPermitsListView.getPermitFile($(this))" ></a>';
}
WorkPermitsListView.getPermitFile = function (e) {
var grid = $("#workPermitsGrid").data("kendoGrid");
$(grid.tbody).on("click", "#permitFile", function (e)
{
var row = $(this).closest("tr");
var rowIndex = $("tr", grid.tbody).index(row);
var id = grid._data[rowIndex].Id;
$.ajax(
{
url: PTWApp.getSitePrefix() + '/File/GetWorkPermitFile',
type: 'GET',
dataType: 'json',
data:
{
workPermitId: id
},
success: function (data) {
var link = document.createElement('a');
document.body.appendChild(link);
link.href = PTWApp.getSitePrefix() + data.file.Url;
link.click();
},
error: function () {
alertBox("Error downloading");
}
});
});
}
WorkPermitsListView.onDataBind = function(arg) {
kgrid = $("#workPermitsGrid").data("kendoGrid");
localStorage["kendo-grid-options"] = JSON.stringify(kgrid.getOptions());
}
/** Returns an events checkmark image
*
* #param model object reference to the work permit model
* #returns Html with img tag set to the right status image
*/
WorkPermitsListView.addEventImg = function (model)
{
if (model.IsEvent === true)
{
return '<img src="../img/checkmark.png" class="statusIcon" style=" display: block; margin-left: auto; margin-right: auto; width: 20%"/>'
}
else
{
return '';
}
}
/** Triggers a work permit search using the parameters as criteria
*
* #param ominisearch string text typed by the user
*
* #param includeContractorActivePermitsOnly bool tells the search if the user wants to retrieve only contractors with active permits
*
* #param includeInactiveContractors bool tells the search if the user wants to include inactive/deleted contractors in the search
*
* #returns nothing
*/
this.searchWorkPermit = function (omnisearch,workPermitID,contractorName,status)
{
if (status === null ||
status === "")
{
status = PTWApp.EnumWorkPermitStatus.Undefined; // default status
}
console.log("Omnisearch: "+omnisearch + " | contractorID: "+ contractorName + " | WorkPermitID: "+workPermitID + " | Status: "+status);
var grid = $("#workPermitsGrid").data("kendoGrid");
grid.dataSource.query({
page: 1,
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: false,
filter: {
"omnisearch": omnisearch,
"workPermitID": workPermitID,
"contractorID": contractorID,
"status": status
}
/** logic: "and",
filter: [
{field: "Id", operator: "eq", value: workPermitID},
{field: "ContractorName", operator: "contains", value: contractorName},
{field: "Status", operator: "eq", value: status}
] **/
});
$(".searchContextInfo").text("Search results");
}
/** Retrieves a parameter value from the query string (url)
*
* #param param string parameter name to look for
*
* #return string Returns the parameter value if found
*/
this.getParameterValue = function (param)
{
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
/** Displays the advanced search div
*
* #param none
*
* #return none
*/
this.showAdvancedSearch = function ()
{
this.advancedSearchWindow = $("#advancedSearchDiv");
this.advancedSearchWindow.kendoWindow(
{
width: 370,
height: 320,
title: "Advanced Work Permit Search",
visible: false,
modal: true,
actions: ["Close"]
}
);
this.advancedSearchWindow.data("kendoWindow").center().open();
}
/** Creates an AJAX request to save the new work permit information
*
* #param none
*
* #return none
*/
this.createNewWorkPermit = function ()
{
window.location = 'WorkPermit.aspx?pid=-1';
}
Can someone please help me identify what is wrong?
I can see that you have configured the grid to use 'serverFiltering', also you're using two different configurations, the first with a variable and then inside the grid config itself, I would recomend to only use one, I've udpated your grid config to this:
$("#workPermitsGrid").kendoGrid({
autoBind: false,
dataSource: {
transport: { read: PTWApp.getSitePrefix() + "/Workpermits" },
schema:{
model:{
id: "Id",
fields:{
Id:{type:"number" },
StartDate:{type:"date" },
EndDate:{type:"date" }
}
}
},
pageSize: 10,
},
scrollable: {
virtual: true
},
sortable: true,
dataBound: WorkPermitsListView.onDataBind,
pageable: {
numeric: false,
previousNext: false
},
noRecords: { template: "<div class='noRecordsDiv'>No permits to display. Use search for more or contact the administrator for assistance.</div>" },
filterable: true,
columns: [
{
command: {
click: WorkPermitsListView.editWorkPermit,
name: "modify",
text: gridDefaultActionName
},
width: "70px"
},
{
field: "Id",
title: "Permit #",
width: "7%" ,
headerAttributes: { style: "white-space: normal"}
},
{
field: "Status",
title: "Status",
template: "#= WorkPermitsListView.addStatusImg(data)#",
width: "7%",
filterable:false,
headerAttributes: { style: "white-space: normal"},
editor: workPermitsListView.selectPermit
},
{
field: "StartDate",
title: "Start Date",
template: "#= PTWApp.ConvertDate(data.StartDate)#",
width: "7.5%",
filterable:false,
headerAttributes: { style: "white-space: normal"}
},
{
field: "EndDate",
title: "End Date",
template: "#= PTWApp.ConvertDate(data.EndDate)#",
width: "7.5%",
filterable:false,
format:"{0:MMM dd yyyy}",
headerAttributes: { style: "white-space: normal"}
},
{
field: "ContractorName",
title: "Contractor",
width: "8.5%",
headerAttributes: { style: "white-space: normal"}
},
{
field: "ContractorSupervisorName",
title: "Supervisor",
width: "8.5%",
filterable:false,
headerAttributes: { style: "white-space: normal"}
},
{
field: "ContractorSupervisorPhone",
title: "Phone #",
template: "#: WorkPermitsListView.formatPhone(ContractorSupervisorPhone) #",
width: "7.5%",
filterable:false,
headerAttributes: { style: "white-space: normal"}
},
{
field: "RequestedBy",
title: "Requester",
width: "7.5%",
filterable:false
},
{
field: "Attachments",
title: "Files",
template: "#= WorkPermitsListView.addFileImg(data)#",
filterable:false,
width: "6%"
},
{
field: "IsEvent",
title: "Events",
template: "#= WorkPermitsListView.addEventImg(data)#",
width: "5.5%"
},
{
field: "Description",
title: "Work Description",
width: "33.5%"
//, attributes: { "class": "shortText" } }
}
]
});
Try it and let me know if it works.
I'm using Gijgo Grid and I have added a button to the grid rows using the cellDataBound event but I can't get the button click event to fire. Anyone any idea what the issue may be ?
CompanyUsersGrid.on('cellDataBound', function (e, $displayEl, id, column, record) {
if ('Subscribed' === column.field) {
if (record.Subscribed === '1') {
$displayEl.html('<Span style="color: green;">Subscribed</Span>');
}
else if (record.Subscribed === '0') {
$displayEl.html('<button type="button" id="btnCompanyUserSubscribed" style="width: 92px;" class="btn btn-danger">Renew</button>');
}
}
});
$('#btnCompanyUserSubscribed').on('click', function (e) {
alert('Button has been clicked')
})
I think that would be best if you use column.renderer about this. You should assign the click event right after the creation of the element.
<table id="grid"></table>
<script>
var subscribeRenderer = function (value, record, $cell, $displayEl) {
var $btn = $('<button type="button" class="btn btn-danger">Renew</button>').on('click', function () {
alert('clicky');
});
$displayEl.empty().append($btn);
};
$('#grid').grid({
dataSource: '/Players/Get',
columns: [
{ field: 'ID', width: 56 },
{ field: 'Name' },
{ field: 'subscribe', renderer: subscribeRenderer }
]
});
</script>
The code above should be also useful with cellDataBound event.
Give the event click function inside the columns and use cellDataBound.Like this
reportGrid = $('#eventReportData').grid({
primaryKey: 'UserPrivilegeRequestsID',
autoLoad: false,
responsive: true,
bodyRowHeight: 'fixed',
dataSource: '/Admin/GetDiscrepencyReport',
columns: [
{
field: 'UserName', title: 'Trainer', sortable: true,
events: {
'click': function (e) {
var userName = e.data.record.UserName;
popupGrid(userName);
}
}
},
{ field: 'Organization', title: 'Organization', sortable: true },
{ field: 'Country', title: 'Country', sortable: true },
{ field: 'Action', width: 170, renderer: editManager }
],
params: { sortBy: 'UserName', direction: 'desc' },
pager: { limit: 10, sizes: [5, 10, 15, 20] },
});
reportGrid.on('cellDataBound', function (e, $displayEl, id, column, record) {
if ('UserName' === column.field) {
$displayEl.html("<div data-toggle='modal' data-target='#myModal2' >" + record.UserName + "</div>");
}
});
function popupGrid(userName) {
alert(userName);
}
Make it a function and do it like this:
$(document).ready(function () {
CompanyUsersGrid.on('cellDataBound', function (e, $displayEl, id, column, record) {
if ('Subscribed' === column.field) {
if (record.Subscribed === '1') {
$displayEl.html('<Span style="color: green;">Subscribed</Span>');
}
else if (record.Subscribed === '0') {
$displayEl.html('<button type="button" id="btnCompanyUserSubscribed" style="width: 92px;" class="btn btn-danger">Renew</button>');
$('#btnCompanyUserSubscribed').on('click', CompanyUserSubscribed);
}
}
});
});
function CompanyUserSubscribed() {
alert('Button has been clicked');
}
you can create your button this way:
$(document).ready(function () {
function Edit(e, type) {
alert("Button was clicked for row: " + e.data.record.recid)
}
grid = $("#myGrid").grid({
dataKey: "recid",
uiLibrary: "bootstrap",
dataSource: //SomeURL,
columns: [
{ field: 'recid', title: 'RecordID', width: 20, resizable: true, align: 'center' },
{ title: 'Edit', field: 'Edit', width: 15, type: 'icon', icon: 'glyphicon-pencil', tooltip: 'Edit', events: { 'click': Edit }, align: 'center' }
]
});
});
Most important part is calling your Edit function here:
events: { 'click': Edit }
I am using a Kendo UI grid in my AngularJS app, I am adding, editing and displaying records but I am not able to get the pagination to work. Currently I have set the pageSize to 2 and if I add a new record to the data it shows it on the same page instead of a new one.
Following is my angular js controller code for configuring the Kendo UI grid:
$scope.keyPersonList = new kendo.data.ObservableArray([
{person1: 'Kiran', policyStatusID: 1 },
{person1: 'Kadam', policyStatusID: 2 }]);
$scope.mainGridOptions = {
dataSource: {
pageSize: 2,
schema: {
model:
{
id: "id",
fields: {
person1: { editable: true, type: "string" },
policyStatusID: { editable: true, valuePrimitive: true }
}
}
}
//total: 10,//function () { return $scope.keyPersonList.length; },
//serverPaging: false,
//serverSorting: false
},
selectable: "row",
//toolbar: kendo.template(angular.element("#toolbarTemplate").html()),
toolbar: '<button class="btn btn-default mrn-10-lft" id="btnAddNewPerson" name="btnAddNewPerson" type="button" role="button" ng-click="addNewPerson($event)">Add New<span class="glyphicon glyphicon-plus color-green pad-10-lt"></span></button>',
sortable: true,
pageable: {
previousNext: true,
numeric: true,
messages: {
empty: "No items",
display: "{2} items",
pageSizes: true
}
},
height: 400,
columns: [
{
hidden: true,
field: "id"
}, {
field: "person1",
title: "Person 1",
width: "200px",
type: "string",
validation: {
required: true
}
}, {
field: "policyStatusID",
title: "Policy Status",
width: "75px",
editor: function (container, options) {
var input = $('<input id="ctrlPolicyStatus" name="policyStatusID" data-text-field="name" data-value-field="name" data-bind="value:' + options.field + '" k-ng-model="policyStatusID">');
input.appendTo(container);
// initialize a dropdownlist
input.kendoDropDownList({
dataSource: dropDownDataSource,
valuePrimitive: true
}).appendTo(container);
},
validation: {
required: true
}
},
{
command:
[{ text: "customDelete", className: "btn-person btn-person-Delete", click: deletePersonData },
{ text: "customArchive", className: "btn-person btn-person-archive", click: archivePersonData },
{ text: "customUnarchive", className: "btn-person btn-person-unarchive", click: unArchivePersonData }],
title: "",
width: "40px"
}
],
editable: true
};
Following is my HTML code:
<kendo-grid k-options="mainGridOptions" id="grdKeyPeople"
k-data-source="keyPersonList"
k-on-change="selected = data">
</kendo-grid>
Thank you for your help in advance.
The issue was, I had set the data source both in the mainGridOptions and also in the directive k-data-source. I removed the directive k-data-source and it worked for me.
I have a grid where each row has a select drop down box in with values.
When an item is selected, how can I make the grid reload to reflect the change?
The reason I want to do this is because the item selected from the drop down effects an amount in another column.
Here is the code for my dropdown:
function shippingModelSelect(container, options)
{
$('<input required data-text-field="modelName" data-value-field="modelId" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: [
{
"modelName": "Individual shipping cost",
"modelId": 1
},
{
"modelName": "Based on weight",
"modelId": 2
},
{
"modelName": "Based on value",
"modelId": 3
}
],
close: function()
{
handleChange();
}
});
}
My handle change function:
var gridAlert = $('#gridAlert');
var handleChange = function(input, value) {
if(input && value)
{
detail = 'Product <b>'+input[0].name+'</b> changed to <b>'+value+'</b>';
gridAlert.html('<b>Changes saved!</b><p>'+detail+'</p>');
gridAlert.fadeIn('slow', function(){
setTimeout(function(){
gridAlert.fadeOut();
}, 2000)
});
}
dataSource.sync();
}
And finally my grid setup:
dataSource = new kendo.data.DataSource({
serverPaging: true,
serverSorting: true,
serverFiltering: true,
serverGrouping: true,
serverAggregates: true,
transport: {
read: {
url: ROOT+'products/manage'
},
update: {
url: ROOT+'products/set-product',
type: "POST",
data: function(data)
{
data.dateAdded = kendo.toString(data.dateAdded, 'yyyy-MM-dd hh:ii:ss')
return data;
}
}
},
pageSize: 20,
sort: {
field: 'id',
dir: 'desc'
},
error: function(e) {
alert(e.errorThrown+"\n"+e.status+"\n"+e.xhr.responseText) ;
},
schema: {
data: "data",
total: "rowcount",
model: {
id: "id",
fields: {
id: {
type: 'number',
editable: false
},
SKU: {
type: "string"
},
name: {
type: "string"
},
dateAdded: {
type: "date",
format: "{0:yyyy/MM/dd hh:mm}",
editable: false
},
shippingModel: {
type: "string"
},
shippingModelId: {
type: "number"
},
price: {
type: "number"
}
}
}
}
})
$('#productGrid').kendoGrid({
dataSource: dataSource,
autoBind: true,
columns: [
{
field: "image",
title: "Image",
width: 30,
template: "#= '<img title=\"'+alt+'\" src=\"images/'+image+'\"/>' #"
},
{
field: "SKU",
title: "SKU",
width: 50,
headerTemplate: "<abbr title=\"Stock Keeping Unit - A unique identifier for this product\">SKU</abbr>"
},
{
field: "stockQuantity",
title: "Quantity",
width: 30
},
{
field: "name",
title: "Name",
width: 200
},
{
field: "dateAdded",
title: "Date Added",
width: 80,
template: "#= niceDate #"
},
{
field: "shippingModelId",
title: "Shipping Model",
width: 50,
editor: shippingModelSelect,
template: "#= shippingModel #"
},
{
field: "price",
title: "Price",
width: 80,
//format: "{0:c}",
template: "#= '£'+price.toFixed(2)+'<br /><span class=\"grey\">+£'+shipping+' shipping</span>' #"
}
],
sortable: true,
editable: true,
pageable: {
refresh: true,
pageSizes: [10, 20, 50]
},
scrollable: false,
reorderable: true,
edit: function(e) {
var value;
var numericInput = e.container.find("[data-type='number']");
// Handle numeric
if (numericInput.length > 0)
{
var numeric = numericInput.data("kendoNumericTextBox");
numeric.bind("change", function(e) {
value = this.value();
handleChange(numericInput, value);
});
return;
}
var input = e.container.find(":input");
// Handle checkbox
if (input.is(":checkbox"))
{
value = input.is(":checked");
input.change(function(){
value = input.is(":checked");
handleChange(input, value);
});
}
else
{
// Handle text
value = input.val();
input.keyup(function(){
value = input.val();
});
input.change(function(){
value = input.val();
});
input.blur(function(){
handleChange(input, value);
});
}
}
}
)
You will need to do two things.
Wait for changes to finish syncing
Tell the grid to re-read the datasource
This should do both for you
dataSource.bind("sync", function(e) {
$('#productGrid').data("kendoGrid").dataSource.read();
});
For more info see the datasource sync event and datasource read method on their docs site.