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

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

Related

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

DGrid Editor - Changing the Displayed Value when Trying to Edit a Text Cell

I'm using a DGrid editor column to edit the contents of a store. Of the fields that I want to be able to edit, one is an object. When I click on the field to edit it, what I want is for the value displayed in the editor to match the value displayed by the grid when not editing. The cell formatting just shows the value of the object, but when I click on the field to edit it, instead of the object's value, I instead the field is populated with '[object Object]'. I can still edit it (though the results of doing so is that the field will display 'undefined' until I refresh the page, but I could just force a refresh after the change), but can't seem to get it to show what I want.
Here's the set up code:
// build the store
this.postStore = Observable(Memory({
data: posts
}));
var formatCategory = function(object, data, cell) {
cell.innerHTML = object.category.value;
};
var formatAuthor = function(object, data, cell) {
cell.innerHTML = object.author.value;
};
var formatDate = function(object, data, cell) {
cell.innerHTML = new Date(object.dateCreated).toISOString();
};
// the columns displayed in the grid
var columns = [
selector({
field: 'checkbox',
label: ' ',
selectorType: 'radio',
width:33
}),
{
label: "Author",
field: "author",
width: 120,
renderCell: formatAuthor
},
editor({
label: "Title",
field: "title",
editor: "text",
editOn: "click",
width: 200
}),
editor({
label: "Text",
field: "text",
editor: "text",
editOn: "click",
width:500
}, Textarea),
editor({
label: "Category",
field: "category",
editor: "text",
editOn: "click",
width: 150,
renderCell: formatCategory
}),
{
label: "Date",
field: "date",
renderCell: formatDate,
width: 120
}
];
if (this.postGrid) {
this.postGrid.set("store", this.postStore);
} else {
var SelectionGrid = new declare([OnDemandGrid, Selection, Keyboard, editor, selector, DijitRegistry, ColumnResizer]);
this.postGrid = new SelectionGrid({
store: this.postStore,
columns: columns,
selectionMode: 'none',
sort: [{attribute: "date", descending: false}]
}, this.postGridDiv);
this.postGrid.startup();
this.postGrid.on("dgrid-select, dgrid-deselect", lang.hitch(this, this._postSelected));
this.postGrid.on("dgrid-datachange", lang.hitch(this, function(evt){
var cell = this.postGrid.cell(evt);
var post = cell.row.data;
if (cell.column.field === "title") {
post.title = evt.value;
} else if (cell.column.field === "text") {
post.text = evt.value;
} else if (cell.column.field === "category") {
post.category.value = evt.value;
}
this._updatePost(post);
}));
Instead of defining a renderCell function, define a get function (which is used to transform the value before it is even sent to renderCell) and a set function (which is used to transform data back before it's sent to a store when saving edits).
Something like:
get: function (object) {
return object.category.value;
},
set: function (object) {
return { value: object.category };
}
See also the documentation.

Slick Grid - formatters.delete not showing in the grid when adding values by input type text

I have a grid with two columns: name and delete. When the user enters to an input text a value and clicks the button, that value is added to the grid. The problem is that the column "Delete" doesn't work,the column "Delete" doesn't display anything. See the code below:
grid = new Slick.Grid("#mygrid", gridData.Selections, columns, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
$("#btnAddValue").click(function () {
var newItem = { "SelectionName": $("#Name").val() };
$('#pickListName').val('');
var item = newItem;
data = grid.getData();
grid.invalidateRow(data.length);
data.push(item);
grid.updateRowCount();
grid.render();
});
var columns = [
{ id: "SelectionName", name: "Name", field: "SelectionName", width: 420, cssClass: "cell-title", validator: requiredFieldValidator },
{ id: "Id", name: "Delete", field: "Id", width: 80, resizable: false, formatter: Slick.Formatters.Delete }];
var options = {
enableAddRow: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true};
How should solve this?
Thank you

Kendo UI Grid - Binding to navigation properties

I am using the Kendo UI grid and am display a role of models. Each model has a navigation property, and I am trying to display a field that exists in this navigation property.
//schema for my kendo data source
schema: {
data: function (data) {
return data || [];
}
}
......................................................
$("#FAAFreqGrid").kendoGrid({
dataSource: FAADS,
columns: [
{ field: "Id", title: "Freq ID", format: "{0:c}", width: "120px" },
{ field: "Frequency", title: "Frequency Test" format: "{0:c}", width: "120px" },
{ field: "FREQ_POOL", title: "FAATEST", format: "{0:c}", width: "120px" },
{ command: ["edit", "destroy"], title: " ", width: "250px" }
],
toolbar: ["create"],
editable: "inline",
pageable: true
});
If I go to my Web API Url, I get a json response of:
[{"$id":"1","Frequency":"164.1375","FREQ_POOL":{"$id":"2","IsAM":true,......etc}
FREQ_POOL is my navigation property, and it has the data I want. Frequency exists and displays in my grid properly. But my FREQ_POOL field says [object Object], and if I try to say "FREQ_POOL.IsAM", it says IsAM is not defined. I cannot get it to bind to any property I can bind to any other non-navigation field. How do I make this work? The data exists in the JSON object that is returned, but the binding just isn't working correctly. Thanks.
You could set a template for the column in question, like this:
$("#grid").kendoGrid({
columns: [ {
field: "name",
template: "<strong>#: name.first#, #: name.last# </strong>"
}],
dataSource: [ { name: { first: 'Jane', last: 'Doe' } }, { name: { first: "John", last: 'Doe' } } ]
});
the template can then be used to show object in the dataset
more info, you could find here
For the editing, you could then also define the cell editor, with an extra template or function, more info about that, you could find here.

Formatting of values in dynamic Kendo grid

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" },
],

Categories

Resources