How can I refresh "footer" on Kendo Ui Grid using JQuery - javascript

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));

Related

Kendo Grid Automatically Fit Column Width except for Specific Column

I am looking for a way to let column(index = n) (by index number) or column(headingText = 'Address') (by column name) fill the gap on my kendo grid.
I know how to automatically fit column widths for a Kendo Grid:
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function() {
var grid = $("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: {
type: "number"
},
ShipCountry: {
type: "string"
},
ShipCity: {
type: "string"
},
ShipName: {
type: "string"
},
OrderDate: {
type: "date"
},
ShippedDate: {
type: "date"
}
}
}
},
pageSize: 15
},
height: 550,
sortable: true,
resizable: true,
pageable: true,
dataBound: function() {
for (var i = 0; i < this.columns.length; i++) {
this.autoFitColumn(i);
}
},
columns: [{
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "ShipCountry",
title: "Ship Country"
},
{
field: "ShipCity",
title: "Ship City"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShippedDate",
title: "Shipped Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "OrderID",
title: "ID"
}, {
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "ShipCountry",
title: "Ship Country"
},
{
field: "ShipCity",
title: "Ship City"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShippedDate",
title: "Shipped Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "OrderID",
title: "ID"
}
]
});
});
</script>
</div>
<style>
#grid>table
{
table-layout: fixed;
}
</style>
I made a fiddle, but I don't know how to link in kendo grid:
https://jsfiddle.net/jp2code/p6cu5r29/2/
I could HARD CODE the column widths:
columns: [
{ field: "name", width: "200px" },
{ field: "tel", width: "10%" }, // this will set width in % , good for responsive site
{ field: "age" } // this will auto set the width of the content
],
But I'd like the grid to be more dynamic.
I can remove the empty space in a grid by leaving the autoFitColumn off of the last column:
<style>
.k-grid {
width: 700px;
}
</style>
<div id="grid1"></div>
<script>
function getMasterColumnsWidth(tbl) {
var result = 0;
tbl.children("colgroup").find("col").not(":last").each(function (idx, element) {
result += parseInt($(element).outerWidth() || 0, 10);
});
return result;
}
function adjustLastColumn() {
var grid = $("#grid1").data("kendoGrid");
var contentDiv = grid.wrapper.children(".k-grid-content");
var masterHeaderTable = grid.thead.parent();
var masterBodyTable = contentDiv.children("table");
var gridDivWidth = contentDiv.width() - kendo.support.scrollbar();
masterHeaderTable.width("");
masterBodyTable.width("");
var headerWidth = getMasterColumnsWidth(masterHeaderTable),
lastHeaderColElement = grid.thead.parent().find("col").last(),
lastDataColElement = grid.tbody.parent().children("colgroup").find("col").last(),
delta = parseInt(gridDivWidth, 10) - parseInt(headerWidth, 10);
if (delta > 0) {
delta = Math.abs(delta);
lastHeaderColElement.width(delta);
lastDataColElement.width(delta);
} else {
lastHeaderColElement.width(0);
lastDataColElement.width(0);
}
contentDiv.scrollLeft(contentDiv.scrollLeft() - 1);
contentDiv.scrollLeft(contentDiv.scrollLeft() + 1);
}
$("#grid1").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Employees"
},
pageSize: 6,
serverPaging: true,
serverSorting: true
},
height: 430,
pageable: true,
resizable: true,
columnResize: adjustLastColumn,
dataBound: adjustLastColumn,
columns: [{
field: "FirstName",
title: "First Name",
width: "100px"
}, {
field: "LastName",
title: "Last Name",
width: "150px"
}, {
field: "Country",
width: "100px"
}, {
field: "City",
width: "100px"
}, {
field: "Title",
width: "200px"
}, {
template: " "
}]
});
</script>
But, I don't want to always leave the last column super wide to fill the page.
I am looking for a more generic example showing how to let column(index = n) or column(headingText = 'Address') be the column that fills the gap.
I did it! Sharing with others:
function refreshGridColumns(grid, skipField) {
var index = -1;
console.log('refreshGridColumns: grid.columns.length = ' + grid.columns.length);
var columns = grid.options.columns;
// find address column and do not autofit it so that the grid fills the page
for (var i = 0; i < grid.columns.length; i++) {
if (0 < columns.length) {
console.log('refreshGridColumns: field = ' + columns[i].field);
if (columns[i].field == skipField) { // columns[i].title -- You can also use title property here but for this you have to assign title for all columns
index = i;
} else {
grid.autoFitColumn(i);
}
} else {
grid.autoFitColumn(i);
}
console.log('refreshGridColumns: i = ' + i);
}
console.log('refreshGridColumns: index = ' + index);
}
Kudos to Jayesh Goyani for this answer:
https://stackoverflow.com/a/34349747/153923

KendoUI filterable display internal error status:500

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.

Kendo UI grid comboBox undefined on focus out?

I have working on Keno UI grid and I have added a comboBox as a column in the grid which also supports autocomplete feature. Apparently, comboBox is working fine but when I type half of world and focus out of the comboBox cell then it shows undefined. I have tried to handle it on combobox change event, but it is still showing undefined value? Below is my code for combobox and grid.
function productDropDownEditor(container, options) {
$('<input id="ProductDropDown" style="width:250px;" data-bind="value:' + options.field + '"/>')
.appendTo(container).kendoComboBox({
dataSource: dataSource,
autoBind: false,
dataTextField: 'ProductName',
dataValueField: 'ProductID',
filter: "contains",
suggest: true,
index: 3,
change: function (e) {
debugger;
var cmb = this;
// selectedIndex of -1 indicates custom value
if (cmb.selectedIndex < 0) {
cmb.value(0); // or set to the first item in combobox
}
},
close: function (e) {
debugger;
var cmb = this;
}
});
And here is following code for kendo grid.
$(function () {
$("#grid").kendoGrid({
columns: [
{
field: "Products", width: "250px",
editor: productDropDownEditor,
title: "Product",
template: "#=Products.ProductName#",
attributes: {
"class": "select2_single"
}
},
{ field: "PurchasePrice", width: "150px" },
{ field: "PurchaseQuantity", width: "150px" },
{ field: "SaleRate", title: "Sale Rate", width: "150px" },
{ field: "Amount", title: "Amount", width: "150px" },
{ command: "destroy", title: "Delete", width: "110px" },
],
editable: true, // enable editing
pageable: true,
navigatable: true,
sortable: true,
editable: "incell",
toolbar: ["create"], // specify toolbar commands
edit: function (e) {
//debugger;
//// var parentItem = parentGrid.dataSource.get(e.model.PurchaseID);
////e.model.set("ShipCountry", parentItem.Country);
//if (e.model.isNew()) {
// // set the value of the model property like this
// e.model.set("PropertyName", Value);
// // for setting all fields, you can loop on
// // the grid columns names and set the field
//}
},
//editable: "inline",
dataSource: {
serverPaging: true,
requestStart: function () {
kendo.ui.progress($("#loading"), true);
},
requestEnd: function () {
kendo.ui.progress($("#loading"), false);
},
serverFiltering: true,
serverSorting: true,
batch: true,
pageSize: 3,
schema: {
data: "data",
total: "Total",
model: { // define the model of the data source. Required for validation and property types.
id: "Id",
fields: {
PurchaseID: { editable: false, nullable: true },
PurchasePrice: { nullable: true },
PurchaseQuantity: { validation: { required: true, min: 1 } },
SaleRate: { validation: { required: true, min: 1 } },
Amount: { type: "number", editable: false },
Products: {
nullable: false,
validation: { required: true},
defaultValue: {ProductID:1, ProductName:"Googo" },
//from: "Products.ProductName",
parse: function (data) {
debugger;
if (data == null) {
data = { ProductID: 1};
}
return data;
},
type: "object"
}
}
}
},
batch: true, // enable batch editing - changes will be saved when the user clicks the "Save changes" button
change: function (e) {
debugger;
if (e.action === "itemchange" && e.field !== "Amount") {
var model = e.items[0],
type = model.Type,
currentValue = model.PurchasePrice * model.PurchaseQuantity;//formulas[type](model);
if (currentValue !== model.Amount) {
model.Amount = currentValue;
$("#grid").find("tr[data-uid='" + model.uid + "'] td:eq(4)").text(currentValue);
}
//if (e.field == "Products") {
// $("#grid").find("tr[data-uid='" + model.uid + "'] td:eq(0)").text(model.Products);
//}
}
},
transport: {
read: {
url: "#Url.Action("Read", "Purchase")", //specify the URL which should return the records. This is the Read method of the HomeController.
contentType: "application/json",
type: "POST", //use HTTP POST request as by default GET is not allowed by ASP.NET MVC
},
parameterMap: function (data, operation) {
debugger;
if (operation != "read") {
// post the products so the ASP.NET DefaultModelBinder will understand them:
// data.models[0].ProductID = data.models[0].Product.ProductID;
var result = {};
// data.models[0].ProductID = $("#ProductDropDown").val();
for (var i = 0; i < data.models.length; i++) {
var purchase = data.models[i];
for (var member in purchase) {
result["purchaseDetail[" + i + "]." + member] = purchase[member];
}
}
return result;
} else {
var purchaseID = $("#hdnPurchaseId").val();
//output = '{ purchaseID: ' + purchaseID + '}';
data.purchaseID = purchaseID; // Got value from MVC view model.
return JSON.stringify(data)
}
}
}
},
}).data("kendoGrid");

ExtJs - Editor Grid Panel add column for delete rows

I've created Editor Grid Panel but I couldn't add column for delete rows. I've tried few versions but without any result.This is my code.I would like add delete column with row like icon not like tbar button.
this.libraryListGrid = new Ext.grid.EditorGridPanel({
clicksToEdit: 1,
colModel: new Ext.grid.ColumnModel({
columns: [{
dataIndex: 'name',
editable: !this.config.viewOnly,
editor: new Ext.form.TextField({
allowBlank: true,
controllerThis: this,
listeners: {
blur: function(item){
var record =item.getValue();
var valid = true;//this.controllerThis.libraryListGrid.isValidValue(record);
item.setValue(record);
item.setValue(record);
}
}
}),
header: ' ',
id: 'name'
},
{
header: ' ',
text:'delete',
items: [{
handler: function(grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
//rec.store.remove();
alert("Delete " + rec.get('name'));
grid.getStore().remove(rec);
//grid.getStore().removeAt(rowIndex);
}
}]
}
]
}),
ds: this.libraryListDataStore,
height: 200,
width: 'auto',
isValidValue: function(field) {
return true;
var valid = new RegExp(/|s|/).test(field);
if(field.match(/^[s]/)){
helpsys.replaceFlashArea("Can not contain spaces!");
valid = false;
}else{
if(!field.length >= 10){
helpsys.replaceFlashArea("lenght is longer then 10,10 is mximal size for this field!");
valid = false;
}
}
this.store.each(function (record){
if (record.id != this.gridEditor.record.id && record.get('name') == this.getValue()
&& record.get('name').length > 0) {
valid = false;
return false;
}
}, field);
if (!valid) {
helpsys.replaceFlashArea(helpsys.locale.jobs.agent_environment.agent_environment_variables_validation);
}
this.allowEdit = valid;
return valid;
},
allowEdit: true,
forceValidation: true,
loadMask: true,
renderTo: 'libraryListGrid',
selModel: new helpsys.AddRowSelectionModel(),
stripeRows: true,
tbar: [{
disabled: this.config.viewOnly,
text: helpsys.locale.agent_environments.add_variable_button,
handler : function(){
// access the Record constructor through the grid's store
var Plant = this.libraryListGrid.getStore().recordType;
var p = new Plant({
});
this.libraryListGrid.stopEditing();
this.libraryListDataStore.insert(0, p);
this.libraryListGrid.startEditing(0, 0);
},
scope: this
}],
view: new Ext.ux.grid.BufferView({
autoFill: true,
forceFit: true,
getRowClass: function(record, rowIndex, rp, ds){
}
})
});
}
I also want to do this type of requirement.I have used this code, try it.Its work for me.
var userCM = new Ext.grid.ColumnModel([
{
header: "UserName",
width: 15,
sortable: true,
dataIndex: 'username',
editor:new Ext.form.TextField({
readOnly:true
})
},{
xtype:'actioncolumn',
width: 5,
align: "center",
header: "Action",
id:'userEmailDeleteId',
icon: '../images/delete.png',
tooltip: 'Delete Email',
handler: function(grid,rowIndex) {
// write your logic here
}
}])
Thanks for help but I've found other an interesting way for that.
this.libraryListGrid = new Ext.grid.EditorGridPanel({
clicksToEdit: 1,
colModel: new Ext.grid.ColumnModel({
columns: [{
dataIndex: 'name',
editable: !this.config.viewOnly,
editor: new Ext.form.TextField({
allowBlank: true,
controllerThis: this,
listeners: {
blur: function(item){
var record =item.getValue();
var valid = this.controllerThis.libraryListGrid.isValidValue(item);
if(valid){
item.setValue(record);
}else{
item.setValue(record);
}
}
}
}),
header: ' ',
id: 'name'
},
{
header: '',
menuDisabled: true,
width: 35,
dataIndex: '',
fixed: true,
renderer: this.renderActions
}
]
}),
ds: this.libraryListDataStore,
height: 200,
width: 'auto',
isValidValue: function(field) {
var valid = true;
valid = field.match(/\s/);
if(!valid){
helpsys.replaceFlashArea("Can not contain spaces!");
return false;
}else{
if(!field.length >= 10){
helpsys.replaceFlashArea("lenght is longer then 10,10 is mximal size for this field!");
return false;
}
}
this.store.each(function (record){
if (record.id != this.gridEditor.record.id && record.get('name') == this.getValue()
&& record.get('name').length > 0) {
helpsys.replaceFlashArea(helpsys.locale.jobs.agent_environment.agent_environment_variables_validation);
return false;
}
}, field);
return valid;
},
allowEdit: true,
listeners: {
rowclick: {
fn: onRowClick,
scope: this
}
},
forceValidation: true,
loadMask: true,
renderTo: 'libraryListGrid',
selModel: new helpsys.AddRowSelectionModel(),
stripeRows: true,
tbar: [{
disabled: this.config.viewOnly,
text: helpsys.locale.agent_environments.add_variable_button,
handler : function(){
// access the Record constructor through the grid's store
var Plant = this.libraryListGrid.getStore().recordType;
var p = new Plant({
});
this.libraryListGrid.stopEditing();
this.libraryListDataStore.insert(0, p);
this.libraryListGrid.startEditing(0, 0);
},
scope: this
}],
view: new Ext.ux.grid.BufferView({
autoFill: true,
forceFit: true,
getRowClass: function(record, rowIndex, rp, ds){
}
})
});
},
renderActions: function(value, metadata, record, rowIndex, colIndex, store){
var columnValue = '<div class="rowAction deleteAction" ><div class="iconLinkIcon deleteIcon"></div></div>';
return columnValue;
}

Kendo UI Grid Refesh on Dropdown Selection

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.

Categories

Resources