Formatting of values in dynamic Kendo grid - javascript

I am trying to figure out how to format individual values in a Kendo grid bound to a dynamic data source.
The challenge is that the columns are not fixed and the format is not even consistent throughout the column.
From what I can tell Kendo supports format strings at the column level using
columns:[{field:Name,format:{1:c}}]
However this solution is not suitable since it sets the format for the entire column.
I have also found a template based solution that lets you format your data manually using notation like this
columns:[{field:Name,template: "#= kendo.toString(kendo.parseDate(SomeDate, 'yyyy-MM-dd')}]
However, again this is too hard coded for me since it assumes a single type in the column.
I am looking for a way to specify in the data source itself what the type a value is. Is that possible?
Something like this
data = [{field:SomeField,Value:4,Format:{1:c}}]

It turns out you can solve this with a custom template. This will run formatting on every value.
for (var c = 0; c < grid.Cols.length; c++) {
grid.Cols[c].template = "#= FormatValue(" + grid.Cols[c].field + ")#";
}
function FormatValue(value) {
return kendo.toString(value, "c0")//currency formatting
}

If you are going to bind dynamic data source then there in no need to format value in column or feilds. It will automatic adjust with the data.
You should use this pattern
fields: {
EventID: { editable: true, nullable: false },
EventName: { validation: { required: true} },
UserID: { validation: { required: true} },
EventDate: { validation: { required: true} },
EventTimeFrom: { validation: { required: true} },
EventTimeTo: { validation: { required: true} }
}
columns: [
{ field: "EventID", title: "Event ID" },
{ field: "EventName", title: "Event Name" },
{ field: "UserID", title: "User ID" },
{ field: "EventDate", title: "Event Date" },
{ field: "EventTimeFrom", title: "Start Time" },
{ field: "EventTimeTo", title: "End Time" },
],

Related

Kendo grid when create a new row, auto populate fields with values from existing row

I have 5 columns (kendo grid) that gets data from the database. What I'm trying to do is, whenever I add a new row, I want certain columns to be auto populated dynamically.
For example, I have Name, country, state, value, and effDate columns.
Name, country, state fields are editable = false. So users are only able to edit value and effDate fields.
If Name = John, Country = USA, State = Alaska, Value = 123, effDate = 9/11/2019 and when I add a new row, I want Name, country, state fields to be populated with Name - John, Country - USA, State - Alaska. Value and effDate should only be empty so that users can add new data.
I'm currently using template.
I tried this to populate country column, but it's not showing anything.
template: "#= Country #"
Is there a way to pre-populate dynamically when create a new row?
Part of my grid codes model:
{
id: "NameKey",
HouseKey: houseKey,
fields: {
Name: { editable: false },
Country: { editable: false },
State: { editable: false },
Value: {
validation: {
pattern: {
value: "^[0-9.]{0,10}$",
message: "Only numbers"
},
required: {
message: "Value is required"
},
}
},
EffDate: { validation: { required: true }, type: "date", format: "{0:MM/dd/yyyy}" },
},
...
part of the columns
columns: [
{ field: "Name", template: "#=(Name== '') ? 'Fields are auto populated' : Name#", title: "Name", width: 250 },
{ field: "Country", template: "#=(Country== '') ? 'Fields are auto populated' : Countr#", title: "Country", width: 210 },
{ field: "State", template: "#=(StateName == '') ? 'Fields are auto populated' : State#", title:"State", width: 200 },
{ field: "Value", title:"Value", width: 200 },
{
field: "EffDate", title;"Date", template: "#= kendo.toString(kendo.parseDate(data.EffDate, 'yyyy-MM-dd'), 'MM/dd/yyyy') #", width: 140
},
],
You can use the beforeEdit event to achieve that behaviour. That event is called whenever the user tries to edit or create a new entry in the grid. It receives the current model, which you can change according to your needs:
beforeEdit: function(e) {
let model = e.model;
if (model.isNew()) {
model.Name = "John";
model.Country = "USA";
model.State = "Alaska";
}
}
Demo

How to get Regular Expression in IgGrid cell (Infragistics)?

how can i have a regular expression on a igTextEditor in igGrid Updating?
i tried to use validate option but it didn't worked.
$("#schedulerTable").igGrid({
columns: $scope.schedulerColumns,
width: "87%",
height: "300px",
fixedHeaders: true,
autoGenerateColumns: false,
autofitLastColumn: true,
autoCommit: true,
renderCheckboxes: true,
responseDataKey: "results",
dataSource: $scope.schedulerData,
updateUrl: "",
primaryKey: 'Id',
features: [
{
name: "Updating",
generatePrimaryKeyValue: function (evt, ui) {
nextPrimarykey -= 1;
ui.value = nextPrimarykey;
},
enableAddRow: true,
enableDeleteRow: true,
editMode: "row",
columnSettings: [
{
columnKey: "Id",
editorType: "numeric",
editorOptions: {
readOnly: true
}
}, {
columnKey: "Time",
editorType: "text",
editorOptions: {
},
validatorOptions: {
regExp: /^[a-zA-Z]{1}[a-zA-Z0-9_\.\-]*\#\w{2,10}\.\w{1,10}$/,
onblur: true,
onchange: true
},
required: true,
validation: true,
defaultValue: "00:00"
},
{
columnKey: "Mo"
},
{
columnKey: "Tu"
},
{
columnKey: "We"
},
{
columnKey: "Th"
},
{
columnKey: "Fi"
}]
}]
});
i want to achive a time picker in the Time Column but that doesn't exist so i try to get only time in the textEditor by regular expression.
the grid gets loaded with columns named Time, Mo- Friday.
if you click on add in grid you can click in the input field and fill your time. the time should get validated before clicking on done and show a error message.
to see how the table look like: https://codepen.io/ablablabla/pen/PJLbJz
The lack of validation is because the validatorOptions belong to the editorOptions (as those get passed down to whatever editor you choose as provider). The validation: true only gets some defaults, which really won't do much for a text field besides the required.
And then the RegExp option (which is for an email in the snippet above as far as I can tell) has been pattern since 15.2 :) So in the end for that time column you can try:
//...
editorOptions: {
validatorOptions: {
pattern: /^\d{1,2}\:\d{2}$/,
onblur: true,
onchange: true
},
},
//..
Here's an updated codepen: https://codepen.io/anon/pen/YrgYxj
Edit: Or if you want to set the error message:
//...
editorOptions: {
validatorOptions: {
pattern: {
expression: /^\d{1,2}\:\d{2}$/,
errorMessage: "Time should match a pattern like 00:00"
},
onblur: true,
onchange: true
},
},
//..
Depending on your goals you could also use a Mask Editor or a Date Editor as provider. Also the obligatory docs link: https://www.igniteui.com/help/iggrid-updating
P.S. Bind to an empty array to avoid the error for that first row that has no values and more importantly primary key.

How To display Sql Server timestamp column in kendo grid java script

i have a timestamp column in one of my sql server table for maintaining row versioning ,
but i dont know how to display its value on kendo grid ,
this is required because my entities wont updating records with null values in that column , by displaying timestamp value on grid , i will take it back when updating records .
this is my kendo grid schema
schema: {
errors: function(response) {
if (response.Voucher && response.Voucher !== "True") {
return response.Voucher;
}
return false;
},
data: "data",
total: "total",
model: {
id: "ID",
fields: {
ID: { editable: false, nullable: true },
FK_Category_ID: { defaultValue: -1, validation: { required: { message: "" } } },
CompanynameAr: { type: "string", validation: { required: { message: " " } } },
CompanynameEn: { type: "string" },
FK_Country_ID: { defaultValue: -1, validation: { required: { message: "" } } },
Address: { type: "string", validation: { required: { message: "" } } },
PoBox: { type: "string" },
Contractno: { type: "number", validation: { required: { message: "" },min:0 } },
Refrence: { type: "number",validation:{min:0}},
RemarksMarketing: { type: "string" },
Active: { type: "string" },
Latitude: { type: "string" },
Longitude: { type: "string" },
RowVersion: {
type: "date", parse: function (value) {
return new Date(value * 1000);
}
}
//Address
}
}
}
here RowVersion is my column that hold timestamp values , parse function is just hit and try for solving particular issue but wont sucessful . so help needed
At the server-side, when adding or updating a record, you should NOT include the timestamp (RowVersion) column in your query (even with a NULL value). SQL Server will automatically generate the value for the RowVersion column on each change to any record. So if you are using plain SQL, remove RowVersion from your SQL; Or if you use Entity Framework Code-First, you may use a [DatabaseGenerated(DatabaseGeneratedOption.Computed)] attribute to inform Entity Framework that it should not update the related column.
Anyway, if you want to display the timestamp (rowversion) value to your user, it is an 8-byte auto-incrementing integer that is usually mapped to a byte[] type and you may use BitConverter.ToInt64() to convert it to a long and show it to the user. But you never need to receive it in your controller on add/update requests because you should not include it in your query.
As you could see on MSDN, an sql server Timestamp value is a .net byte array, so you can't convert it to a Date value.
You can simply make no convertion on the received value and just hide it.

Store calculated data in Column of Kendo Grid

What I'm trying to do is store some data in a specific column that is calculated by using the data from another column.
I currently have a function that returns the number of available licenses for the given Id in JSON
function getAvailableLicenses(id) {
var url = "/Host/Organization/AvailableLicenses/" + id;
$.get(url, function (data) {
return data.AvailableLicenses;
});
}
How do I go about storing this number in a column named "AvailableLicenses"?
Here is my current Grid:
$("#OrganizationGrid").kendoGrid({
dataSource: viewModel.get("orgDataSource"),
filterable: {
extra: false
},
sortable: true,
pageable: true,
columns: [
{ field: "Id", hidden: true },
{ field: "Name", template: "<a href='/Host/Organization/Detail/#:Id#'>#:Name#</a>" },
{ field: "LicenseNumber", title: "Number of Licenses" },
{ field: null, title: "Available Licenses", template: "#= getAvailableLicenses(Id) #" },
{ field: "LicenseExpiration", title: "License Expiration", format: "{0:MM/dd/yyyy}" },
{ field: "State" },
{ field: "Active" }
],
editable: false
});
As you can see, I tried to create a null column with a template that calls the function for the given Id.
By using Fiddler I can see that the function is indeed being called for all of the rows, but the AvailableLicenses column just displays Undefined for every row.
Is there something I'm missing here to get this to work?
I think the better way to do this is on dataSource parse() function
First: you column configuration must change like this:
{ field: "AvalableLicenses", title: "Available Licenses" },
You alaways can use you template .
And second, inside your dataSource() you can add:
schema: {
parse: function(response) {
for (var i = 0; i < response.length; i++) {
response[i].AvalableLicenses= null;
response[i].AvalableLicenses = getAvailableLicenses(response[i].Id)
}
return response;
}
}
EDIT:
If you prefer using you way, I dont see any problem in your configuration, probably your $.get is returning undefined, or something you don't expect.
For conviniance I did an example working.
http://jsfiddle.net/jwocf897/
Hope this help

Kendo UI grid export excel and pdf export, no file created

I am trying to create a kendo grid with excel export. My data is shown precisely as I want it and the grid works fine. However, the saveAsExcel function triggers the excelExport event, but no file is created. Same problem with the pdf export.
Here is my grid options:
grid = $("#grid").kendoGrid({
toolbar:["excel","pdf"],
height: 500,
scrollable: true,
groupable: true,
sortable: true,
filterable: false,
excel: {
allPages:true,
filterable:true
},
excelExport: function(e) {
console.log('Firing Export');
console.log(e.workbook);
console.log(e.data);
},
pdfExport: function(e){
console.log('PDF export');
},
columns: [
{ field: "date", title: "Time", template: "#= kendo.toString(kendo.parseDate(date), 'MM/dd/yyyy') #", width: '120px'},
{ field: "customer", title: "Customer" },
{ field: "amount", title: "Total", format: "{0:c}", width: '70px', aggregates: ["sum"]},
{ field: "paid_with", title: "Payment", width: '130px'},
{ field: "source", title: "Source" },
{ field: "sale_location", title: "Sale Location" }
]
}).data("kendoGrid");
This ajax is called whenever the search parameters for the data is changed. Where I refresh the datasource.
$.ajax({
'url':'/POS/ajax/loadTransactionsDetailsForDay.php',
'data':{
filters
},
'type':'GET',
'dataType':'json',
'success':function(response) {
var dataSource = new kendo.data.DataSource({
data: response.data.invoices,
pageSize: 100000,
schema: {
model: {
fields: {
date: {type: "string"},
customer: { type: "string" },
amount: { type: "number" },
paid_with: {type: "string"},
source: {type:"string"},
sale_location: {type:"string" }
}
}
}
});
grid.setDataSource(dataSource);
grid.refresh();
}
});
The output from my console log is.
Firing Export.
A worksheet object.
Object {sheets: Array[1]}sheets: Array[1]0: Objectlength: 1__proto__: Array[0]__proto__: Object
and and array with these objects for every row in the grid:
0: o
_events: Object
_handlers: Object
amount: 40.45
customer: "customer 1"
date: "2015-11-25T00:00:00-08:00"
dirty: false
employee: 23
paid_with: "Check"
parent: ()
sale_location: "Main"
source: "POS"
uid: "70b2ba9c-15f7-4ac3-bea5-f1f2e3c800d3"
I have the latest version of kendo, I am loading jszip. I am running it on the latest version of chrome.
I have tried all kinds of variations of this code I can think of, including removing my schema, initializing the kendo anew every time in the callback.
Anyone got any idea why this would not work?
Every example on this I can find make it look super simple, just create the grid and call export... So I have to have overlooked something.
I am grateful for any ideas about this.
Thanks.
It could be because the filename is missing.
Here the part with the filename added:
excel: {
allPages:true,
filterable:true,
fileName: "Kendo UI Grid Export.xlsx"
},
You can take a look here : Grid Excel Export
And here for the pdf: Grid Pdf Export
I have some following suggestion.
Can you add kendo deflate pako script file into your code and try.
Then remove the pdf export event and just try to export a pdf with toolbar default functionality..check whether its working or not.
try to add a data-source ajax call with in a grid option using kendo-transport technique with read method. http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-transport

Categories

Resources