Data Entry App with Kendo grid and angularjs // code using kendo ui native functions - kendo-grid

i use kendo grid for a data entry form. it have a grid with four columns. a single row have four input text boxes (one for each column ) for data entry. the first time the grid load it should have a single row with four inputs, with the cursor focused to first input. when user enter some data and press 'enter' key, the focus should move to next cell input in the same row. when you press enter in the last column input, a new row should be added to the grid and the data entered should be saved on the grid. focus should go to new row's first input. all cells should be editable and navigatable with enter key.
Can some one please give me a solution for this in angularjs/ javascript? Im using angularjs with kendo grid.
//-> Grid Start
var d2 = [
{ ConnectionReference: '001', ContractNumber: '', Amount: '', ReferenceNumber: '' },
{ ConnectionReference: '002', ContractNumber: '', Amount: '', ReferenceNumber: '' },
{ ConnectionReference: '003', ContractNumber: '', Amount: '', ReferenceNumber: '' },
{ ConnectionReference: '004', ContractNumber: '', Amount: '', ReferenceNumber: '' }];
var dataSource2 = new kendo.data.DataSource({
//data: data,
transport: {
read: function (e) {
e.success(d2);
},
update: function (e) {
e.success();
},
create: function (e) {
var item = e.d2;
item.Id = d2.length + 1;
e.success(item);
}
},
schema: {
model: {
id: "Id",
fields: {
'ConnectionReference': { editable: true, type: "string" },
'ContractNumber': { editable: true, type: "string" },
'Amount': { editable: true, type: "number" },
'ReferenceNumber': { editable: true, type: "string" }
}
}
}
});
var grid2 = $("#desgrid").kendoGrid({
dataSource: dataSource2,
scrollable: true,
navigatable: true,
toolbar: ["save", "cancel", "create"],
columns: [
{
field: "ConnectionReference",
// attributes: {
// "class": "colclass"
// "navi-text": ""
// },
// headerTemplate: 'Connection Reference',
// template: '<input ng-keydown="AA(this,$event)" type ="text" class="k-fill text-right aa" format-number ng-pattern="/^[0-9]+(\.[0-9]{2})?$/" />',
width: "130px"
},
{
field: "ContractNumber",
// attributes: {
// "class": "colclass"
// "navi-text": ""
// },
// headerTemplate: 'Contract Number',
// template: '<input ng-keydown="AA(this,$event)" type ="text" class="k-fill text-right aa" format-number ng-pattern="/^[0-9]+(\.[0-9]{2})?$/" />',
width: "130px"
},
{
field: "Amount",
// attributes: {
// "class": "colclass"
// "navi-text": ""
// },
// headerTemplate: 'Amount',
// template: '<input ng-keydown="AA(this,$event)" type ="text" class="k-fill text-right aa" format-number ng-pattern="/^[0-9]+(\.[0-9]{2})?$/" />',
width: "130px"
},
{
field: "ReferenceNumber",
// attributes: {
// "class": "colclass"
// "navi-text": ""
// },
// headerTemplate: 'Reference Number',
// template: '<input ng-keydown="AA(this,$event)" type ="text" class="k-fill text-right aa" format-number ng-pattern="/^[0-9]+(\.[0-9]{2})?$/" />',
width: "130px"
}
],
editable: {
createAt: "bottom"
},
navigatable: true
//edit: function onEdit(e) {
// var grid = this;
// var cellIndex = e.container.index();
// var nextCell = e.container.next().eq(cellIndex);
// if (nextCell) {
// e.container.find("input").on("keypress", function (e) {
// if (e.which === 13) {
// $(this).trigger("change");
// grid.closeCell();
// grid.editCell(nextCell);
// }
// });
// }
//},
}).data("kendoGrid");
grid2.tbody.on('keydown', function (e) {
if ($(e.target).closest('td').is(':last-child') && $(e.target).closest('tr').is(':last-child')) {
grid2.addRow();
}
})
// grid2.tbody.on('keydown', function (e) {
// var key = e.keyCode ? e.keyCode : e.which;
// if (key === 13) {
// var focusedElement = $(e.target);
// var nextElement = focusedElement.parent().parent().parent().next();
// var nextElement = focusedElement.next();
// if ($(e.target).closest('td').is(':last-child') && $(e.target).closest('tr').is(':last-child')) {
// if (nextElement.find('input').length > 0) {
// grid2.addRow();
// }
//}
// }
// })
$scope.submitForm = function () {
// $scope.alertMessage = new Message("0", "NIC format is invalid!");
//var fun = $scope.callback();
//var d = $scope.dgGridAddPaymentsEnter.data();
//d.splice(0, 1);
//fun($scope.params.Qty, $scope.dgGridAddPaymentsEnter.data());
}

Related

Problem in binding the data to the kendo multi-select dropdown

I have a kendo grid in angular, which is supposed to have some columns with multi-select dropdown.
When I select the item from the list for the first time, that item gets binded and the second item when selected the gridParams holds the second item selected, but once the API call returns the data, the list binded refreshes to none(no data binded to the dropdownlist).
Below is the code related
{
OC.setReportGridColumns(responsecolumns);
OC.reportsGridOptions = {
dataSource: {
schema: {
data: "Data",
total: "Total",
model: {
fields: OC.GetSchemaFields()
}
},
transport: {
read: function (e) {
gridParams = JSON.parse(JSON.stringify({
CurrentPage: e.data.page,
PageSize: e.data.pageSize,
Sort: e.data.sort,
Filter: e.data.filter
}));
if (gridParams.Filter != undefined) {
var a;
if (gridParams.Filter.filters!= undefined) {
angular.forEach(gridParams.Filter.filters, function (value, key) {
if (value.field === "QuoteStatus") {
value.operator = "in";
a = "'" + value.value + "'";
a = a.replace(",", "','");
value.value = a;
}
});
};
};
ReportService.GetAllAdHocReport(gridParams, '', OC.CustomColumnSelected, TemplateId).then(function (response) {
if (response != '') {
$("li [ui- sref='AdHocReport']").parent().addClass("activelist");
response.Total = response.Data != null && response.Data.length > 0 ? response.Data[0].TotalRecords : 10;
OC.GridConfigDataSource.read();
e.success(response);
OC.hideFilters();
} else {
e.success([]);
}
});
},
},
filterable: {
mode: "row,menu",
extra:false
},
selectable: 'cell',
columns: OC.gridCols,
}
}
}
OC.setReportGridColumns = function (colList) {
var col = JSON.parse(colList).columns;
OC.setfilterDropdown(col);
var cols = col.map(function (value) {
if (value.column == "QuoteStatus") {
return {
field: value.column,
title: value.title,
filterable: OC.filterDropdowns(value.column),
width: value.width,
sortable: true,
};
}
});
}
OC.filterDropdowns = function (column) {
return {
extra: false,
mode: "menu",
multi: true,
cell: {
showOperators: false,
template: function (args) {
/////------****Multi-select Dropdown****------///////
args.element.kendoMultiSelect({
autoBind: true,
dataTextField: "text",
dataValueField: "value",
dataSource: new kendo.data.DataSource({
data: OC.getDataForFilterDropdown(column)
}),
index: 0,
optionLabel: {
text: "--Select--",
value: ""
},
valuePrimitive: true,
});
},
}
}
}

Prevent datasource reloading on change event of kendo grid

I am working on Kendo Grid, On button click, I call a function to reFetch data from db with new Parameters.
function is here
vm.refereshFigure = function (response) {
vm.gridOptions = {
datasource: new kendo.data.DataSource({
type: "odata",
transport: {
read: function (options) {
if (!!$scope.figure.figureId) {
gridService.runQuery(options, $scope.figure.figureId, response).then(function (responseData) {
options.success(responseData.data);
});
}
}
},
schema: {
data: "Data",
total: "Total"
},
change: function (e) {
debugger;
e.preventDefault();
},
pageSize: vm.gridConfigurationJson.PageSize ? vm.gridConfigurationJson.PageSize : 10,
group: vm.JsonGroupingCloumns,
aggregate: vm.aggregatesList,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
filter: !!vm.gridConfigurationJson.Filter
? vm.gridConfigurationJson.Filter.filters
: vm.gridConfigurationJson.Filter,
page: vm.gridConfigurationJson.page,
sort: vm.gridConfigurationJson.sort
}),
dataBound: function (e) {
//if (vm.gridConfigurationJson.PageSize != e.sender.pager.dataSource._pageSize) {
// saveGridConfigration(e);
//}
},
groupable: true,
pageable: {
refresh: true,
pageSizes: [10, 25, 50, 100, 200, "All"],
buttonCount: 5,
},
noRecords: true,
filterable: true,
sortable: {
mode: "multiple",
allowUnsort: true,
showIndexes: true
},
resizable: true,
reorderable: true,
columnMenu: true,
columns: vm.columnsList,
toolbar: ["excel"],
excel: {
allPages: true,
filterable: true,
},
excelExport: function (e) {
try {
var sheet = e.workbook.sheets[0];
for (var rowIndex = 1; rowIndex < sheet.rows.length; rowIndex++) {
var row = sheet.rows[rowIndex];
for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
if (this.columns[cellIndex].type == 'date') {
row.cells[cellIndex].format = "yy-MM-dd hh:mm:ss";
row.cells[cellIndex].value =
kendo.parseDate(row.cells[cellIndex].value, "yyyy-MM-ddTHH:mm:ss");
}
}
}
} catch (e) {
}
var filename = "";
if ($scope.figure.captionView != undefined) {
filename = $scope.figure.captionView;
} else if ($scope.figure.caption != undefined) {
filename = $scope.figure.caption;
}
e.workbook.fileName = filename + ".xlsx";
},
};
$scope.filterChanged(response, undefined, $scope.figure.figureId);
};
It called web api two times. Below is the code in read function which executes two times.
if (!!$scope.figure.figureId) {
gridService.runQuery(options, $scope.figure.figureId, response).then(function (responseData) {
options.success(responseData.data);
});
}
After first Call, It goes Change() event, then call read() again.
Can anyone help me what I am doing wrong?

Kendo Grid - how to remember selected row?

http://dojo.telerik.com/eWakO
Kendo Grid - here how should i modify above code to remember selected row? Example, if i have highlighted 4th row on 1st page and then scrolls to pages and come back to 1st page, then 4th row should be highlighted.
Thanks
Datha
Here is an example from the documentation:
http://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Selection/persist-row-selection-while-paging
It relies on the change and dataBound events to save and restore selected rows by their IDs.
<div id="grid"></div>
<script>
$(function () {
var selectedOrders = [];
var idField = "OrderID";
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Orders"
},
schema: {
model: {
id: "OrderID",
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
height: 400,
selectable: "multiple",
pageable: {
buttonCount: 5
},
sortable: true,
filterable: true,
navigatable: true,
columns: [
{
field: "ShipCountry",
title: "Ship Country",
width: 300
},
{
field: "Freight",
width: 300
},
{
field: "OrderDate",
title: "Order Date",
format: "{0:dd/MM/yyyy}"
}
],
change: function (e, args) {
var grid = e.sender;
var items = grid.items();
items.each(function (idx, row) {
var idValue = grid.dataItem(row).get(idField);
if (row.className.indexOf("k-state-selected") >= 0) {
selectedOrders[idValue] = true;
} else if (selectedOrders[idValue]) {
delete selectedOrders[idValue];
}
});
},
dataBound: function (e) {
var grid = e.sender;
var items = grid.items();
var itemsToSelect = [];
items.each(function (idx, row) {
var dataItem = grid.dataItem(row);
if (selectedOrders[dataItem[idField]]) {
itemsToSelect.push(row);
}
});
e.sender.select(itemsToSelect);
}
});
});
</script>

Highchart Tool-tio show CSV data

I am trying to display csv data in the tooltip of the Highcharts.
Data:
Time,Users,AVG_Sec,Volume,ServerName,InstanceName
11:35 AM ,59,.863,664,server1,int123
11:35 AM ,43,.659,392,server2,int123
11:35 AM ,46,1.347,442,server3,int124
11:35 AM ,49,1.164,702,server2,int125
I am able to display users,avg_sec and volume in the graph.
Please let me know if i can dsplay the servername and instance name in the graph as bars/columns else at least show them in tool tip.
The code so far:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Last Hourly All'
},
tooltip:{
formatter:function(){
return '<b>' + this.series.name + '</b>' +
'<br/><b>X Value:</b> ' + this.x +
'<br/><b>Y Value:</b> ' + this.y +
'<br/><b>Other Data:</b> ' + this.point.ServerName;
}
},
credits: {
enabled: false
},
xAxis: {
categories: [],
labels: {
rotation: -90
}
},
yAxis:[{
startOnTick: false,
title: {
text: 'No of Transactions'
}
}, {
opposite: true,
title: {
text: 'Response Time'
}
}, {
opposite: true,
title: {
text: 'Volume'
}
}, {
opposite: true,
title: {
text: 'Server Name'
}
}, {
opposite: true,
title: {
text: 'Instance Name'
}
}
],
series: []
};
//try.csv
$.get('data/lastHrlyAllTZ1.csv', function(data) {
// Split the lines
var lines = data.split('\n');
//variable declaration
var series = {
data: [],
type: 'spline',
color: '#336633'
};
var series1 = {
yAxis: 1,
data: [],
color: '#FF3399'
};
var series2 = {
yAxis: 2,
data: [],
color: '#9900FF'
};
var series3 = {
yAxis: 3,
data: [],
color: '#660066'
};
var series4 = {
yAxis: 4,
data: [],
color: '#CC99CC'
};
$.each(lines, function(lineNo, line) {
var items = line.split(',');
// header line contains categories
if (lineNo == 0) {
series1.name = items[1];
series.name = items[2];
series2.name = items[3];
series3.name = items[4];
series4.name = items[5];
}
// the rest of the lines contain data with their name in the first position
else {
$.each(items, function (itemNo, item) {
if (itemNo == 0) {
options.xAxis.categories.push(item);
} else if (itemNo == 1) {
//console.log(parseFloat(item));
series1.data.push(parseFloat(item));
} else if(itemNo == 2){
series.data.push(parseFloat(item));
} else if(itemNo == 3){
series2.data.push(parseFloat(item));
}
else if(itemNo == 4){
//alert(item);
series3.data.push(item);
}
else if(itemNo == 5){
series4.data.push(item);
}
});
}
});
options.series.push(series1);
options.series.push(series2);
options.series.push(series3);
options.series.push(series4);
options.series.push(series);
var chart = new Highcharts.Chart(options);
In the tool tip as of now it says "undefined".
It doesnt work, because you push only values into data array, but not define name of parametrs. You should push point as object, where you define name of your parameter and y value.

Highcharts bargraph from json data in angularJS

I have a highcharts bargraph whose values are received from json whose format is as follows:
"bargraph":
[
{
"categories": "['S', 'M', 'T', 'W', 'T', 'F']",
"series1": "[800, 1100, 80, 1800, 1600, 2000]",
"series2": "[800, 1100, 80, 1800, 1200, 800]"
}
]
How can i embed those values for my bargraph in angularJS
HTML Code:
<div id="bargraph" bargraph={{bargraph}}><\div>
Directive:
angular.module('example').directive('bargraph', function () {
element.highcharts({
xAxis: [
{
categories: [] //embed categories value here
},
series: [
{
name: 'series1',
data: [] //Embed series1 data here
},
{
name: 'series2',
data: [] //Embed series2 data here
}
]
})
})
Please provide a suitable way to embed the data from json.
Here is a directive i copied and pasted from my webapp it is how i render highcharts using a directive NOTE: not all of this directive is applicable to you and some of it is specific to what i needed but you get the idea.
lrApp.directive('chart', function () {
return {
restrict: 'E',
template: '<div></div>',
transclude: true,
replace: true,
link: function (scope, element, attrs) {
var chart = null;
var chartsDefaults = {
chart: {
renderTo: element[0],
type: attrs.type || null,
height: attrs.height || null,
width: attrs.width || null,
},
colors: scope.$eval(attrs.colors) || null,
title: {
style: {
display: 'none'
}
},
xAxis: {
//categories: ['{"-7 days"|date_format}','{"-6 days"|date_format}','{"-5 days"|date_format}','{"-4 days"|date_format}', '{"-3 days"|date_format}', '{"-2 days"|date_format}', '{"-1 day"|date_format}', '{$smarty.now|date_format}'],
categories: scope.$eval(attrs.dates) || null,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1,
labels: {
y: 27
}
},
yAxis: {
title: {
text: null
},
min: 0,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1
},
credits: {
enabled: false
},
legend: {
enabled: false
},
plotOptions: {
series: {
shadow: false,
lineWidth: 3
}
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': ' + this.y + '</b>';
}
}
};
//Update when charts data changes
scope.$watch(attrs.value, function (newVal, oldVal) {
if (!newVal.length) return;
// We need deep copy in order to NOT override original chart object.
// This allows us to override chart data member and still the keep
// our original renderTo will be the same
var deepCopy = true;
var newSettings = {};
chartsDefaults.series = newVal;
chartsDefaults.colors = scope.$eval(attrs.colors);
chartsDefaults.xAxis.categories = scope.$eval(attrs.dates);
console.log(chartsDefaults);
chart = new Highcharts.Chart(chartsDefaults);
});
}
}
});
and this is how it used it obviously you would change "line" to bar:
<chart value="stats.sets" dates="stats.days" colors="stats.colors" type="line"></chart>