KendoUI datasource: parseInt of filter value - parsing

I need to filter a Kendo datasource through the following filter item object:
filters: [
{
field: "FIELD",
operator: "lt",
value: "080"
}
]
That means, because of the way data are transmitted, I am trying to test a case like: "013" < "080".
But it does not work out of the box.
Is there a way to define a filter with something like a "parseInt" on the tested values?
Thank you!

Try defining FIELD as a number in model:
schema : {
model: {
fields: {
FIELD : { type: "number" }
}
}
},
If you do so, then FIELD is displayed as 13, 80,... If you want to display FIELD with leading 0, use the following in the column definition of the grid.
{ field: "FIELD", title: "Field", format: "{0:000}" }
Doing this FIELD is considered as a number even that it is displayed as 013, 080...
You should have something like:
var dataSource = new kendo.data.DataSource({
data : entries,
batch : true,
schema : {
model: {
fields: {
FIELD: { type: "number" }
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
columns : [
{ field: "FIELD", title: "Field", format: "{0:000}" }
],
filterable: true
}).data("kendoGrid");
If you want to try it, see it in JSFiddle here
EDIT: Updated code for using format instead of template as Mateo Piazza suggested

Related

Loopback POST array of entry?

I want to insert 10 entries with one query against 10 queries.
I read that it's possible to do it by sending an array like this :
But I get this error:
Do I need to set something? I don't know what to do at all.
Repo with a sample : https://github.com/mathias22osterhagen22/loopback-array-post-sample
Edit:
people-model.ts:
import {Entity, model, property} from '#loopback/repository';
#model()
export class People extends Entity {
#property({
type: 'number',
id: true,
generated: true,
})
id?: number;
#property({
type: 'string',
required: true,
})
name: string;
constructor(data?: Partial<People>) {
super(data);
}
}
export interface PeopleRelations {
// describe navigational properties here
}
export type PeopleWithRelations = People & PeopleRelations;
The problem with your code was :
"name": "ValidationError", "message": "The People instance is not
valid. Details: 0 is not defined in the model (value: undefined);
1 is not defined in the model (value: undefined); name can't be
blank (value: undefined).",
Here in above as in your #requestBody schema, you are applying to insert a single object property, where as in your body are sending the array of [people] object.
As you can see in your people.model.ts you have declared property name to be required, so system finds for the property "name", which obviously not available in the given array of object as primary node.
As you are passing index array, so its obvious error that you don't have any property named 0 or 1, so it throws error.
The below is the code hat you should apply to get insert the multiple, items of the type.
#post('/peoples', {
responses: {
'200': {
description: 'People model instance',
content: {
'application/json': {
schema: getModelSchemaRef(People)
}
},
},
},
})
async create(
#requestBody({
content: {
'application/json': {
schema: {
type: 'array',
items: getModelSchemaRef(People, {
title: 'NewPeople',
exclude: ['id'],
}),
}
},
},
})
people: [Omit<People, 'id'>]
): Promise<{}> {
people.forEach(item => this.peopleRepository.create(item))
return people;
}
You can also use this below
Promise<People[]> {
return await this.peopleRepository.createAll(people)
}
You can pass the array of your people model by modifying the request body.If you need more help you can leave comment.
I think you have a clear solution now. "Happy Loopbacking :)"

Exporting CSV from ui-grid with cell display rather than the source value

I have a table done with ui-grid and this table has a column with cellFilter definition like this:
{ field: 'company', cellFilter: 'mapCompany:row.grid.appScope.companyCatalog' }
My gridMenu custom item is configured like this:
gridMenuCustomItems: [
{
title:'Custom Export',
action: function ($event) {
var exportData = uiGridExporterService.getData(this.grid, uiGridExporterConstants.ALL, uiGridExporterConstants.ALL, true);
var csvContent = uiGridExporterService.formatAsCsv([], exportData, this.grid.options.exporterCsvColumnSeparator);
uiGridExporterService.downloadFile (this.grid.options.exporterCsvFilename, csvContent, this.grid.options.exporterOlderExcelCompatibility);
},
order:0
}
]
The table is displayed correctly, but when I try to export to CSV, the Company column is exported with empty value. Here is my Plunkr.
Any suggestion will be appretiated
References
I did some research and according to ui-grid Issue #4948 it works good when the Company column is filled with an static catalog. Here is a Plunkr demostrating that.
As you mentioned, there is an export issue when the values in the column are not static, so I forked your plunker with a solution that creates the company mapping for each data object and adds it as a key-value once you get the company catalog back:
$http.get('https://api.github.com/users/hadley/orgs')
.success(function(data) {
$scope.companyCatalog = data;
angular.forEach($scope.gridOptions.data, function(item) {
var compMap = uiGridFactory.getMapCompany(item.company, $scope.companyCatalog);
item.mappedCo = compMap;
});
});
I've kept the original company column but made it invisible (rather than overwriting it), so it exports with the rest of the data in the csv. New column defs:
columnDefs: [
{ field: 'name' },
{ field: 'mappedCo', name: 'Company'},
{ field: 'company', visible: false }
]
Also, in the case that you were getting your data from a server, you would have to ensure that the data and the catalog returned before you run the mapping function. This solution may not work in your particular use case; I don't know.
I found a solution to the CSV export to be able to display the cell display value.
My mistake was using row.grid instead of this.grid at the mapCompany cell filter:
columnDefs: [
{ field: 'name' },
{ field: 'company', cellFilter: 'mapCompany:row.grid.appScope.companyCatalog' }
],
The right way to use it is using this:
columnDefs: [
{ field: 'name' },
{ field: 'company', cellFilter: 'mapCompany:this.grid.appScope.companyCatalog' }
],
Here is my Plunkr.

How to specify the kendo schema to use in a div

I have the following code in my View using the kendo grid:
<div id="MyGrid"
data-role="grid"
data-editable="true"
data-toolbar='[{ template: kendo.template($("#ToolbarTemplate").html()) }]'
data-columns='[
{ field: "Description" },
{ field: "Value" },
{ command: [{name: "destroy", template: kendo.template($("#DeleteTemplate").html())}], width: 60}
]'
data-bind="source: MyDataSource">
Then in a script section a have:
kendo.bind($("#MyGrid"), MyViewModel)
Everything is working fine. However, now I'm trying to implement a validation to let the user knows that any of the fields inside the Kendo Grid is required. I saw that it can be done in the schema as follow (Kendo doc link):
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
}
}
}
Is there a way to do the same in the div tag as the rest of the attributes? Does data-schema attribute exist?
Thanks in advance
You are missing the kendo validator initialization part in your code. Please refer the following links for documentation and demo
Documentation
Kendo Validator demo

Update Kendo Grid based On Search Form Post

I've been doing alot of searching but haven't found a clear answer for this. I have a set up textboxes that and a submit button and a Kendo UI grid. I want to post the data to the grid's datasource so that it will return the results based on the criteria. I am not using the MVC wrappers.
EDIT:
I've gotten closer but I can't seem to get the datasource to send the post data when I click submit. I've debugged and in my $("#fmSearch").submit it is hitting the jquery plugin and I've confirmed that it is converting the form data to JSON properly, but it seems as though it it not sending the updated information to the server so that the Action can read it.
Javascript
var dsGalleryItem = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Content("~/Intranet/GalleryItem/SearchGalleryItems")',
type: "POST",
data: $("#fmSearch").serializeFormToJSON(),
cache: false
}
},
schema: {
model: {
id: "galleryItemID",
fields: {
galleryItemID: {
nullable: true
},
imageName: {},
collectionName: {},
categoryName: {},
lastUpdatedOn: { type: "date" }
}
}
}
});
var gvResults = $("#gvResults").kendoGrid({
autoBind:false,
columns: [{
field: "imageName",
title: "Item Name",
template: "<a href='#Url.Content("~/Intranet/GalleryItem/Details/")#=galleryItemID#'> #=imageName#</a>"
}, {
field: "collectionName",
title: "Collection"
}, {
field: "categoryName",
title: "Category"
}, {
field: "lastUpdatedOn",
title: "Last Updated",
format: "{0:M/d/yyyy}"
}
],
selectable: "row",
change: onRowSelect,
dataSource: dsGalleryItem
});
$("#fmSearch").submit(
function (event) {
event.preventDefault();
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
});
MVC Action
[HttpPost]
public JsonResult SearchGalleryItems(string keyword, int? category, int? collection, DateTime? startDate, DateTime? endDate)
{
var galleryItemList = (from g in db.GalleryItems
//where g.imageName.Contains(keyword)
select new GalleryItemViewModel
{
galleryItemID = g.galleryItemID,
imageName = g.imageName,
collectionName = g.collection.collectionName,
categoryName = g.category.categoryName,
lastUpdatedOn = g.lastUpdatedOn
});
var galleryItemCount = Json(galleryItemList.ToList());
return Json(galleryItemList.ToList()); ;
}
The action is not setup to retrieve different data right now I just need to know how to connect the form to the grid.
Found the problem. I had this:
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
It needed to be this:
dsGalleryItem.read($("#fmSearch").serializeFormToJSON());

What is the best way to bind a two dimensional object array to the grid that is also type safe

I have a kendo UI Grid from Telerik
I want to bind a two dimensional object array to the grid. I work in Visual Studio 2012 in ASP.NET MVC. I have a solution where I use a javascript solution. The datatype for the datasource is a two dimensional object array. This is because all the rows and columns need to be dynamic in our solution. Here's the JavaScript code to bind the grid:
function createGrid() {
var url = '#Url.Action("GetSheetData")';
$.get(url, { hospitalId: 100, screenCode: "Ledger", revisionId: 1, applicationUser: "TestUser" }, function (result) {
var columnDefs = result.Columns;
var data = result.Data;
// Now, create the grid using columnDefs as argument
var grid = $("#grid").kendoGrid({
dataSource: {
data: jQuery.parseJSON(data)
},
columns: columnDefs,
height: 430,
editable: "incell",
batch: true,
sortable: {
mode: "single",
allowUnsort: false
},
filterable: {
extra: false,
operators: {
string: { contains: "Contains" }
}
},
scrollable: {
virtual: true
},
navigatable: true
}).data("kendoGrid");
});
}
And the function to post the grid back to the server:
function saveGrid() {
var gridDataArray = $('#grid').data('kendoGrid')._data;
var url = '#Url.Action("SetSheetData")';
$.post(url, {
hospitalId: 100
, screenCode: "Ledger"
, revisionId: 1
, applicationUser: "TestUser"
, dataGrid: JSON.stringify(gridDataArray)
}
, function (result) {
var grid = $("#grid").data("kendoGrid");
});
}
The problem with this method is dat when we call the code:
var gridDataArray = $('#grid').data('kendoGrid')._data;
and post the data with:
JSON.stringify(gridDataArray);
all the items in the stringified object become string types. Even those who are numeric. I want my data to maintain the right datatypes
Does anyone know how to keep my grid data type safe?
Any other solutions that do not contain the JavaScript method are fine as well, as long as it supports a two dimensional object array as a type.
I hope the question is clear. Thanks in advance
1) _data is private (as per the _), you should not really be calling that! ds.data() will do the job.
2) the way you retrieving/storing data is not wrong, but I would suggest you to make your life easier and define kendo Transport properly :
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "http://demos.kendoui.com/service/Products",
dataType: "jsonp"
}
}
3) as far as the types are involved, use model allowing you define types.
var dataSource = new kendo.data.DataSource({
schema: {
model: {
id: "ProductID",
fields: {
//data type of the field {Number|String|Boolean|Date} default is String
UnitPrice: {
type: "number",
defaultValue: 42
}
}
}
}
});

Resources