KendoUI Grid Server Dynamic Column binding in service callback - javascript

I am trying to understand the working of KendoUI Grid. I have successfully returned paged data from the server and server side paging is also working.
But I am having problem with setting column details dynamically i.e. neither the titles show up nor the template, the column header shows the name of bound field. I think the problem is related to when columns are initialized because I get to know about the details of columns after call back from the service.
Here is how I am binding the grid:
$("#kGrid").kendoGrid({
dataSource: {
serverPaging: true,
schema: {
data: "data",
total: "total"
},
pageSize: 10,
transport: {
read: function(options) {
var searchParam = new Model.SearchParamsCM('QuoteDomainTasks', 'QuoteList', false, options.data.page, options.data.pageSize);
seHttpService.GetWithParms('/spa/api/genericrequest', searchParam)
.then(function (result) {
var data = oThis.createJSONFromResults(result.data, oThis);
options.success(data);
},
function(result) {
options.error(result);
});
}
}
},
columns: oThis._gridColumns,
scrollable: false,
pageable: { "refresh": true, "pageSizes": true },
sortable: true,
filterable: true
});
Where oThis._gridColumns is populated inside oThis.createJSONFromResults. This code is in TypeScript.

The data source is only for reading the content of the grid, not its configuration (which only needs to be created once, when setting up the grid). You need to separate these two concerns so that oThis._gridColumns has the column definition when you call $("#kGrid").kendoGrid().
Dynamically changing the column definitions is not really supported by Kendo Grid, so if you need that, your options are:
recreate the whole grid whenever the column definition has to change
change things manually (e.g. if only titles change, you could do that by selecting and editing the elements with jQuery)
try to mess with the internals, e.g. something like the following
(note this is largely untested and might break with new Kendo UI releases)
grid.options.columns = changedColumnDefinition;
grid.table.find(">thead").empty();
grid._columns(grid.options.columns);
grid._thead();

Related

The filter feature in our Kendo Grid only returns records from the first page

We used Kendo UI to build the data grid for our ASP.NET MVC application.
When I try to filter data with Kendo UI, the filter option only permits us to filter records on the 1st page:
image
For example, if I want to filter for grade AO25 on page 3 and am currently on page 1, nothing comes up:
image
Even if I navigate to page 3 and try to filter, it only brings up the records from the 1st page:
image
Even trying to filter for a particular record on the same page (in this case, grade AO25) brings up nothing:
image
The same issues applies to the other columns in our grid.
This is the object we send to the kendoGrid() method (some extraneous details were truncated):
dataSource: {
...
pageSize: #(defaultGridPageSize),
serverPaging: true,
serverSorting: false
},
filterable: true,
sortable: {
mode: "multiple",
allowUnsort: true,
showIndexes: false
},
pageable: {
refresh: true,
pageSizes: [#(gridPageSizes)],
#Html.Partial("_GridPagerMessages")
},
scrollable: false,
dataBound: onDataBound,
columns: [
...
{
field: "Grade",
title: "Grade",
filterable: { multi: true, search: true },
width: 100
},
...
],
I wasn't the one that initially wrote the grid views (the person who did is no longer with us).
I've spent a while searching for a solution (to no avail) browsing the documentation on Telerik's website, and trying out different configurations of the properties of the dataSource object and I wasn't able to get the filter functionality to behave as desired.
Changing the serverFiltering property to true in my .cshtml view page didn't fix the issue.

set selected page number - kendo grid

I am creating a grid using kendo-telrik. In this suppose I am having 100 data. From this in json I have only 10 data(suppose first page contains 10 data in pagination). And I am showing all pages(10 pages for 100 data) all the time.
When I click on another page then get next 10 data and show it in ui. For this I am using page change function of kendo grid and get next 10 data.Now I want to list that data in grid with page which I selected.
For this I create sample which is as - http://jsfiddle.net/pporwal26/y6KdK/76/
var jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-174\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\\\\vMbhdo\\\\TgFSW\\\\42Ioulj0w.txt\"},{\"owner\":\"machine-174admin\",\"path\":\"C:\\\\workarea\\\\bada_data\\\\Employee Database - Copy (7) - Copy.mdb\"}],\"Count\":100,\"total\":100,\"page\":1}");
function nextData(page){
jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-170\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\"},{\"owner\":\"machine-170admin\",\"path\":\"C:\\\\workarea\"}],\"Count\":100,\"total\":100,\"page\":"+page+"}");
createGrid(jsonData);
}
createGrid(jsonData);
function createGrid(jsonData){
$("#grid").kendoGrid({
pageable: true,
scrollable: true,
page: jsonData.page,
pageable: {
pageSize: 2,
refresh: true,
change:function(e){
nextData(e.index);
}
},
dataSource: {
serverPaging: true,
schema: {
data: "FileList",
total: "total"
},
data: jsonData
}
});
}
In this sample when I click on change event than it always show 1 page not the page which I selected. and also want that on each click grid is always create new not add in it. What can I do for that?
Well I know that calling createGrid(jsonData); inside of the nextData function, you're going to create a table for every time you increment, that alone will cause bugs. Have you tried commenting that out?
I've personally never used kendoGrid, so if my answer's no good, I do apologies, but from having had a look online, this seems to work?
Worst case, you do need that change, in which case, can't you target the data inside the table and just over ride it in some other function? A pretty morbid way of doing it would be to delete/destroy the current one in order to make a new one. But it would work I guess?

How can I bind data (in JSON format) from local database to Kendo UI Scheduler?

After doing some tuts of the Kendo UI framework, I'm having problems using one of their widgets. I've only a basic understanding of the framework and this is even my first question ever in StackOverflow so... please spare me from "advanced" answers if possible.
So, here's the thing:
I want to use the Scheduler widget to make a timeline month view with data from a JSON file. The data (in JSON format) I'm planning to use comes from a SQL Server database that is called on the client-side by an Ajax call that connects to a web service. Sample:
Params.type = 'GET';
Params.url = 'LoremIpsum-YeahDomainService.svc/JSON/GetPeople';
Params.dataType = 'json'
To know if the web service is working fine, I tried to retrieve information from the database into a Kendo DropDownList and everything went okay. I did this script:
var getPeople;
getPeople = data.GetPeopleResult.RootResults;
var listPeople = [];
getPeople.forEach(function(person){
var newelement = { 'Name': person.Name, 'value': i, 'color': '#808080' };
listPeople.push(newelement);
});
After doing that script, I used the following script:
$("#dropdownlist").kendoDropDownList({
dataTextField: "Name",
dataValueField: "value",
dataSource: new kendo.data.DataSource ( { listPeople } )
});
As planned, I got all the data I wanted to see in the browser.
Therefore, now I want to produce script for the Kendo Scheduler with a timeline month view like this one without the "Meeting Rooms" section and I want the names of the persons that are called from the database.
Just like with the DropDownList, it doesn't matter if I have 30 or 300 person names. The persons on the Scheduler can't be static because the database will be updated often. In a nutshell, the names of the persons that are shown in the Scheduler must be provided dynamically from the database.
I already used multiple scripts from the Kendo UI Scheduler documentation as all my scripts for the widgets are based on their examples but until now, nothing worked out.
Based on the example provided in the Kendo UI documentation for the timeline month view, I've some of their scripts adapted such as:
dataSource: {
batch: true
transport: {
read: {
url: "http://localhost:50379/LoremImpsum-YeahDomainService.svc/json/GetPeople",
dataType: "json"
group: {
resources: ["People"],
orientation: "vertical"
Also in relation to the Scheduler script, based on the example provided on the Telerik website I did a script that would get the persons names from the database. Here it is:
var result = [];
result[0] = { text: "+getPeople[0]+", value: "1", color: "green" }";
for(i=1; i<getPeople.length(); i++){
resultado[i] = ", { text: "+getPeople[i]+"value: "+(i+1)+", color: "green";
i=i+1;
});
With that script in mind, my idea was to call that array on the resources section of the Scheduler widget as something like this:
resources: [
{
field: "people",
name: "People",
dataSource: [ data: getPeople
]
]
Any ideas or thoughts?
P.S.
I also created some script based on Kendo documentation using Kendo UI Dojo and you can see see exactly the type of view I need there.
To whoever may be interested in the future, I found a way to do this. In a nutshell, very quickly and simple:
resources: [{
field: "Name",
name: "People",
dataTextField: "Name",
dataValueField: "Name",
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "http://localhost:50379/LoremImpsum-YeahDomainService.svc/json/GetPeople"
}
},
schema: {
type: "json",
data: "GetPeopleResult.RootResults"
}
}
),
multiple: true,
title: "name"
}]

Unable to assign a pre-filter on jqGrid during its load time for its state saving

I am using jqGrid and I am required to save its specific state if user has performed some search and the grid shows the records as per search criteria. When user performs search and clicks on edit button to edit the record, I am required to show the grid in last left status of the records shown as per search criteria. Just went around several answers of Oleg, but still unable to get my thing working. My jqGrid code is as under:
$('#grid').jqGrid({
url: GetPath,
datatype: 'json',
mtype: 'POST',
search: true,
postdata: {filters: postfilt, sord: postsord, sidx: postsort },
colNames: // ColumnNamesArray
colModel: //The ColumnModel.
page: postpage,
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 20, 30, 40],
viewrecords: true,
sortname: 'DefaultSortColName',
sortorder: 'DESC',
loadonce: true,
gridview: true,
ignoreCase: true,
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
records: 'records',
repeatitems: false,
userdata: 'userdata',
Id: 'PrimaryKeyId'
},
autowidth: true,
multiselect: false
)};
I am having one common js file inside which the jqGrids code exists. Every time I need to populate a jqGrid, I simply need to call the js file before which I need to set few javascript variables say for example: for specifying url of jqgrid, etc. Notice the variable names postfilt, postsord and postsort. I am simply assigning values to these variables as per my requirement: when my grid is loading for the first time, the filters are blank so as to load the grid with all of the data, and assigning these variables with postdata filter values which I have saved earlier when some filter is being applied by user. The issue I am facing is, my this dynamic filter kind of functionality works fine for the first grid on which I implemented it. But it doesn't works for my other grids on which I am trying to implement it.(Of course the different grid search filters are saved for different grids). I have checked while debugging in Chrome's F12 that my filter variables does shows the proper values which are to be provided for a jqGrids postData filter, but still it loads the jqGrid with all of the data every time and not with the filter when required. I tried several times for calling a function in gridComplete or loadComplete for providing postdata filters after getting loaded with my grid, but still being unsuccessfull on filling my jqGrid with last provided search criteria on its first load. Where am I being wrong in providing the criterias for jqgrid so as to load it in its last left state when it is loaded for the first time ? Any help is appreciated.
Edit: One of my saved postdata search filter for jqGrid is as under:
{"groupOp":"AND","rules":[{"field":"ClientName","op":"cn","data":"client"}]}
The main reason of your problem is the wrong parameter which you use. JavaScript is case sensitive. There are no postdata parameter. So it will be just ignored by jqGrid. There are exist postData parameter instead. So to include the filter and to set the initial sorting in the request to url: GetPath you need do the following:
$('#grid').jqGrid({
...
search: true,
postData: {filters: postfilt },
sortname: postsort,
sortorder: postsord,
...
});
In the same way Id property of jsonReader will be ignored. You should use id instead. Moreover jqGrid merge default properties of jsonReader (see the documentation) with the values included in the grid options. So you don't need to include the default properties like root: 'rows', page: 'page' and other. jsonReader should looks like
jsonReader: {
repeatitems: false,
id: 'PrimaryKeyId'
}

JQGrid getGridParam not returning ID of data item

I have a grid that is using local data generated from an external ajax request (by external I mean not using the inbuilt ajax of jqgrid)
the data from the ajax request is passed into the grid as local data and the grid is set to loadonce.
window.grid = $(window.tableName).jqGrid({
datatype: "local",
data: DataFromResponse,
height: "auto",
autowidth: true,
hidegrid: false,
ignoreCase: true,
loadonce: true,
pager: window.pagerName,
rowNum: 10,
viewrecords: true,
gridview: true,
caption: '',
colNames :[cols],
colmodel :[]{cols},
gridComplete: function() {
CreateButtons();
});
As you can see the grid is basic at this stage, however we need to add some buttons within a column named 'buttons' we use the CreateButtons method to do this.
The
function CreateButtons(){
var grid = $(window.tableName);
var data = grid.jqGrid('getGridParam', 'data');
$.each(data, function(index, item){
var cl = item._id_;
alert(cl);
});
}
the alert of this function should give me the id of the row as set by the grid but it is not working any ideas
The property _id_ exist in internal data parameter only if the data loaded from remote source (datatype is "json" of "xml") and the option loadonce: true was used. If one load the data locally (one uses datatype: "local") then _id_ is not exist.
If you correctly fill the grid the data specified by data parameter (DataFromResponse in your case) is array of items which contains id property together with the other properties used to fill the column data. One other option is specifying of key: true for some column. In the case the id for the row will be get from the column.
If you don't specified and id information (which is very bad) and you need to access all local data inclusive the ids generated by jqGrid you need get two jqGrid options: _index and data. The object _index contains as properties all ids of the grid. The value of the id property is integer index in data array which corresponds the id. So you can use for-in loop to enumerate all ids of the grid (you need enumerate properties of _index). See the answer and this one for details.
You wrote additionally that you created buttons in a column of the grid inside of gridComplete. The approach seems me not good. It's better to use custom formatter instead together with gridview: true option (see the answer). Moreover I don't recommend you to use gridComplete at all. It's better to use loadComplete. See the answer for details.

Categories

Resources