How to set schema and column property in Kendu Grid dynamically - kendo-ui

I am using kendu grid with report data,grid is working perfectly in normal case but my problem is that column and schema property of grid will not be static, that's why i want to add it dynamically,but I am unable to set it.
Here is my code:
$(document).ready(function () {
var obj = {
fields: {
}
};
var Column1;
$("#grid").kendoGrid({
dataSource: {
type: "data",
transport: {
read: function (options) {
$.ajax({
type: "GET",
url: "http://localhost:3833/Service1.svc/GetJSON1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var t2 = msg.GetJSON1Result;
var data1 = $.parseJSON(t2.data);
Column1 = t2.columns;
var t11 = Column1;
obj = {
fields: {
}
};
$.each(Column1, function (i, value) {
obj.fields[value.field] = { type: "number" };
}
);
var Schema1 = {
model: obj
}
var gridDetails = $("#grid");
**//Setting schema to grid but it's not effective**
gridDetails.schema = Schema1;
**//Setting schema to grid but it's not effective**
gridDetails.columns = Column1;
options.success(data1);
options.success(Schema1);
options.success(Column1);
}
});
}
},
pageSize: 50,
serverFiltering: false ,
serverSorting: false,
serverPaging: false,
},
height: 550,
reorderable: true,
filterable: true,
sortable: true,
pageable: true,
scrollable: true,
resizable: true,
groupable: true
});
});
please help me. I am new to kendu
Regards,
Ajeet Kumar

To change the grid columns you need to destroy it first and then initialize it again. Here is some code:
var grid = $("#grid").data("kendoGrid");
var options = grid.options;
grid.destroy();
options.columns = [ /* set the columns */ ];
grid.destroy();
$("#grid").empty().kendoGrid(options);

Related

Using fetch method inside Kendo UI grid.template

How to return value from .fetch() method inside grid.template ?
$("#grid-single-user-groups").kendoGrid({
dataSource: assignedUsersDataSource,
toolbar: ["create"],
columns: [
{
field: "UserID", width: "100%",
editor: userDropDownEditor,
template: function(userID) {
//here I can return everything, and its visible in grid cell
//return "BAR"
allUsersDataSource.fetch(function() {
//Here everything is UNDEFINED
return "FOO";
var data = this.data();
console.log(data.length);
for (var idx = 0, length = data.length; idx < length; idx++) {
console.log(data.length); //show right length
console.log(data[idx].UserName);// //show right UserName
if (data[idx].UserNameID === userID.UserID) {
return userID.Login; //UNDEFINED
//return "foo"; //UNDEFINED
}
})
edit:
allUsersDataSource is Kendo DataSource:
var allUsersDataSource = new kendo.data.DataSource({
transport: {
read: {
url: API_URL + "frank/getusers",
dataType: "json"
}
},
});
results JSON:
[{"UserNameID":"2","UserName":"foo","Surname":"foo2","Login":"foo3","GroupName":"admin"},]
edit2:
trying with read() function instead od fetch, with below code:
template: function(userID) {
allUsersDataSource.read().then(function() {
var view = allUsersDataSource.view();
console.log(view[0].Login)// displays right Login
return view[0].Login; // displays "undefined" in grid cell
});
}
edit3:
My entire code where I whant to use DropDown inside Grid cell:
var allUsersDataSource = new kendo.data.DataSource({
transport: {
read: {
url: API_URL + "frank/getusers",
dataType: "json"
}
},
});
allUsersDataSource.fetch(function() {
allUsers = allUsersDataSource.data();
})
var assignedUsersDataSource = new kendo.data.DataSource({
transport: {
read:{
url: API_URL+"frank/getassignedusers/"+documentId,
dataType: "json"
},
create: {
type: "POST",
url: API_URL+"frank/addusertodocument",
dataType: "json"
},
destroy:{
type: "POST",
url: API_URL+"frank/removeuserdocument",
dataType: "json"
},
},
pageSize: 4,
schema: {
model: {
fields: {
UserName: { editable: false, nullable: true },
Surname: { editable: false, nullable: true },
UserID: { field: "UserID", defaultValue: 1 },
GroupName: { editable: false, nullable: true },
}
}
}
});
$("\#grid-single-user-groups").kendoGrid({
dataSource: assignedUsersDataSource,
filterable: true,
scrollable: false,
toolbar: ["create"],
pageable: true,
columns: [
{
field: "UserID", width: "100%",
editor: userDropDownEditor,
title: "Agent",
template: function(userID) {
for (var idx = 0, length = allUsers.length; idx < length; idx++) {
if (allUsers[idx].UserNameID === userID.UserID) {
return userID.Login;
}
}
}
},
{ command: "destroy" }
],
editable: true,
remove: function(e) {
console.log("Removing", e.model.name);
}
});
function userDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataTextField: "Login",
dataValueField: "UserNameID",
filter: "contains",
dataSource: allUsersDataSource
})
}
JSON DataSources - assignedUsersDataSource:
[{"UserID":"198","UserName":"Paw","Surname":"yui","Login":"ddz","GroupName":"ddd"},...]
JSON DataSources - allUsersDataSource:
[{"UserNameID":"198","UserName":"Paw","Surname":"yui","Login":"ddz","GroupName":"ddd"},...]
edit4:
corrected sample datasource:
var assignedUsersDataSource = new kendo.data.DataSource({
data: [{"UserID":"198","UserName":"Paw","Surname":"Mu","Login":"pc","GroupName":"ad"}]
});
var allUsers = new kendo.data.DataSource({
data: [{"UserNameID":"198","UserName":"Paw","Surname":"Mu","Login":"pc","GroupName":"ad"},{"UserNameID":"199","UserName":"Jakub","Surname":"Ch","Login":"jc","GroupName":"ki"}]
});
So to avoid cluttering up the comments here is a possible answer to your problem:
http://dojo.telerik.com/INukUVoT/4
If you now select the item from the dropdown it is changing the id as it retains the last selected item in the selection when you go in and out of it. The reason the name stays the same is a simple one. It's looking in the wrong place for the value to display.
You are simply doing the following:
Look at all the values in the allusers store and then if i get a match of id's just show the value in the model's Login value rather than the value that was found in the data item in the Login.
So you are currently going through a needs loop. you literally could change your template to:
template: "#=data.Login#" rather than having to loop around.
what you seemingly want to do is have one column which is a user object or defined as an id either way will work as you can see in my new examples.
the first grid is binding the UserID property to the grid and then presenting back the value from the dropdown's datasource (you need to ensure that you set the valuePrimitive property to true so it binds only the value and not the object.
the second grid binds the full object and just so you see what is being bound i am stingify'ing the object and putting that into the grid.

Change Kendo Grid Cell With Ajax Response When Another Cell Changes

Using a Kendo grid with 3 columns, I have an event that fires when the first column is changed that makes an ajax call and returns some data. I want to update the second column with the returned data but I'm not having any luck and I'm not even sure if this is the correct approach. I can change the second column with static data by adding a change event to my datasource of my grid, but that of course doesn't help. The only examples I can seem to find show changing another column with client side data, not data returned from the server. Here's what I have so far:
$("#manualStatsGrid").kendoGrid({
dataSource: this.GetManualStatisticsDataSource(),
sortable: true,
pageable: false,
filterable: true,
toolbar: ["create"],
editable: "inline",
messages: {
commands: {
create: "Add New Statistic"
}
},
edit: function (e) {
var _this = _manualStats;
var input = e.container.find(".k-input");
var value = input.val();
input.keyup(function(){
value = input.val();
});
$("[name='Statistic']", e.container).blur(function(){
var input = $(this);
$("#log").html(input.attr('name') + " blurred " + value);
//valid the GL account number
$.ajax({
type: "GET",
url: _this.ValidateGlUrl,
dataType: 'json',
data: { glNumber: value },
success: function (response) {
var newDescription = response.Data.description;
console.log(newDescription);
//change description column here?
},
error: function (response) {
console.log(response);
}
});
});
},
columns: [
{ field: "Statistic" },
{ field: "Description" },
{ field: "Instructions" },
{ command: ["edit", "destroy"], title: " ", width: "250px"}
]
});
}
this.GetManualStatisticsDataSource = function () {
var _this = _manualStats;
var dataSource = {
type: "json",
transport: {
read: {
type: "POST",
url: _this.GetManualStatisticsUrl,
dataType: "json"
},
update: {
type: "POST",
url: _this.UpdateManualStatisticsUrl,
dataType: "json"
},
create: {
type: "POST",
url: _this.CreateManualStatisticsUrl,
dataType: "json"
},
destroy: {
type: "POST",
url: _this.DeleteManualStatisticsUrl,
dataType: "json"
}
},
schema: {
model: {
id: "Statistic",
fields: {
Statistic: {
type: "string",
editable: true,
validation: { required: true, pattern: "[0-9]{5}.[0-9]{3}", validationmessage: "Please use the following format: #####.###" }
},
Description: { editable: false },
Instructions: { type: "string", editable: true }
}
}
}
Inside the edit event, you have e.model. The model has the method set() which can change any dataItem's property value:
edit: function (e) {
...
var editEvent = e; // Creates a local var with the edit's event 'e' variable to be available inside the 'blur' event
$("[name='Statistic']", e.container).blur(function() {
...
$.ajax({
...
success: function(e, response) { // 'e' inside this callback is the 'editEvent' variable
e.model.set("Description", response.Data.description); // e.model.set() will change any model's property you want
}.bind(null, editEvent) // Binds the 'editEvent' variable to the success param
});
});
Working demo
Made this snippet of top of my head. Tell me if there is something wrong with it.

jqGrid getGridParam('colModel') missing information

I would like capture the colModel for my jqGrid when the page unloads and store it in session so the next time the user comes to the page it can be loaded automatically. But, the information returned by ('#contract_grid').getGridParam('colModel') is missing part or all of the information in searchoptions for the grid columns.
Any idea why this is or how to capture the full colModel? The grid works great on the initial load but without the other searchoptions params, the filter bar features/menus don't work when I refresh the page from the colModel stored in session.
Create the default colModel for the grid
var defaultColModel =
[
{name:'REQUESTID'
,index:'requestID'
,label:'Request ID'
,search:true
,stype:'text'
,width:75
,key:true
,hidden:false
},
{name:'REQUESTEDDATE'
,index:'requestedDate'
,label:'Request Date'
,sorttype:"date"
,search:true
,width:50
,searchoptions:{
dataInit:function(el){jQuery(el).daterangepicker(
{
arrows:false
, dateFormat:'yy-mm-dd'
, onClose: function(dateText, inst){ jQuery("#contract_grid")[0].triggerToolbar();}
, onOpen: function() {
jQuery('div.ui-daterangepickercontain').css({"top": jQuery('#mouseY').val() + 'px', "left": jQuery('#mouseX').val() + 'px' });
}
});
}
}
,hidden:false
},
{name:'BUSINESSOWNERPERSONID'
,index:'businessOwnerPersonID'
,label:'Business Owner'
,search:true
,stype:'select'
,width:100
,hidden:false
,searchoptions: {
dataUrl: 'cfc/com_common.cfc?method=getAjxPeople&role=businessOwnerPersonID',
buildSelect: function(resp) {
var sel= '<select><option value=""></option><option value="7583,1636">My Reports</option>';
var obj = $.parseJSON(resp);
$.each(obj, function() {
sel += '<option value="'+this['lk_value']+ '">'+this['lk_option'] + "</option>"; // label and value are returned from Java layer
});
sel += '</select>';
return sel;
},
dataEvents: [{
type: 'change',
fn: function(e) {
alert(this.value)
}
}]
}
}
];
When user navigates away from page, save the grid to session so it loads when they come back
$(window).on('beforeunload', function(){
takeSnapshot();
});
function takeSnapshot(){
var gridInfo = new Object();
gridInfo.colModel = jQuery('#contract_grid').getGridParam('colModel');
gridInfo.postData = jQuery('#contract_grid').jqGrid('getGridParam', 'postData');
var snapshotData = JSON.stringify(gridInfo);
$.ajax({
url: "actions/act_filter.cfc?method=takeSnapshot",
type: "POST",
async: false,
data: {gridName:'contract_grid'
,gridParamName:'contractGridParams'
,filterData:snapshotData
}
});
}
Create grid variable
var myGrid = jQuery("#contract_grid").jqGrid({
url: 'cfc/com_ajxRequestNew.cfc?method=getReqJSON&returnformat=json',
datatype: 'json',
postData: {filters: myFilters},
mtype: 'POST',
search: true,
colModel: defaultColModel,
altRows: true,
emptyrecords: 'NO CONTRACTS FOUND',
height: 400,
width: 1200,
sortname: lastSortName,
sortorder: lastSortOrder,
page: lastPage,
pager: jQuery('#report_pager'),
rowNum: lastRowNum,
rowList: [10,20,50,100],
viewrecords: true,
clearSearch: false,
caption: "Contracts Dashboard",
sortable: true,
shrinkToFit: false,
ajaxSelectOptions: {type: "GET"},
gridComplete: function() {
//set the selected toolbar filter values
var myFields = JSON.parse(myFilters);
//set fields in form at top. filter contains index value so get corresponding name value because its used in the column label #gs
if ( myFields['rules'].length > 0 ) {
for (var i=0; i < myFields['rules'].length; i++ ) {
$.each(defaultColModel, function(j) {
if(this.index == myFields['rules'][i]['field'] ) {
thisFieldName = this.name;
jQuery('#gs_' + thisFieldName).val( myFields['rules'][i]['data'] );
}
})
}
}
}
});
jQuery("#contract_grid").navGrid('#report_pager',{
edit:false,
add:false,
del:false,
search:false,
refresh:false
}).navButtonAdd("#report_pager",{ caption:"Clear",title:"Clear Filters", buttonicon :'ui-icon-trash',
onClickButton: function() {
jQuery.ajax({
url: "/assets/js/ajx_clearFilter.cfm?showHeader=0",
async: false,
type: "POST",
data: ({variableName:'session.contractGridParams'})
});
myGrid[0].clearToolbar();
}
}).navButtonAdd("#report_pager",{ caption:"Restore",title:"Restore Default Grid Columns and Filters", buttonicon :'ui-icon-refresh',
onClickButton: function() {
window.location = '?page=dsp_requestListingNew&clearSession=1';
}
}).navButtonAdd("#report_pager",{
caption: "Export",
title: "Export to Excel",
buttonicon :'ui-icon-document',
onClickButton: function(e){
jQuery("#contract_grid").jqGrid('excelExport',{url:'includes/act_requestListingExport.cfm'});
}
}).navButtonAdd("#report_pager",{
caption: "Columns",
buttonicon: "ui-icon-calculator",
title: "Select and Reorder Columns",
jqModal: true,
onClickButton: function(e){
$('#contract_grid').jqGrid('columnChooser', {
dialog_opts: {
modal: true,
minWidth: 470,
show: 'blind',
hide: 'explode'
}
});
}
}).navButtonAdd("#report_pager",{
caption: "Save",
title: "Save Snapshot",
buttonicon :'ui-icon-disk',
onClickButton: function(e){
takeSnapshot(0);
$('#fltrFrmLink').click();
}
});
jQuery("#contract_grid").jqGrid('filterToolbar', {
stringResult : true
, searchOnEnter : true
, autoSearch : true
, beforeClear : function() {
//set sortnames
var sn = jQuery("#contract_grid").jqGrid('getGridParam','sortname');
//set sort orders
var so = jQuery("#contract_grid").jqGrid('getGridParam','sortorder');
so = "desc";
//set grid params
jQuery("#contract_grid").jqGrid('setGridParam',{ sortorder:so, sortname:sn });
}
});
colModel returned by ('#contract_grid').getGridParam('colModel') on unload. searchoptions is missing everything for REQUESTEDDATE. Part of dataEvents and all of buildSelect are missing for BUSINESSOWNERPERSONID.
[{"name":"REQUESTID",
"index":"requestID",
"label":"Request ID",
"search":true,
"stype":"text",
"width":75,
"key":true,
"hidden":false,
"title":true,"lso":"",
"widthOrg":75,"resizable":true,"sortable":true},
{"name":"REQUESTEDDATE",
"index":"requestedDate",
"label":"Request Date",
"sorttype":"date",
"search":true,
"width":50,
"searchoptions:{},
"hidden":false,
"title":true,
"lso":"",
"widthOrg":50,
"resizable":true,
"sortable":true,"stype":"text"},
{"name":"BUSINESSOWNERPERSONID",
"index":"businessOwnerPersonID",
"label":"Business Owner",
"search":true,
"stype":"select",
"width":100,"hidden":false,
"searchoptions":{"dataUrl":"cfc/com_common.cfc?method=getAjxPeople&role=businessOwnerPersonID",
"dataEvents":[{"type":"change"}]},
"title":true,
"lso":"",
"widthOrg":100,
"resizable":true,
"sortable":true}]
JSON don't support serialization of functions. So the functions from searchoptions.dataInit, searchoptions.buildSelect and all other which you use in colModel will be discarded after you use JSON.stringify.
It's important to know which version of jqGrid/free jqGrid or Guriddo jqGrid JS you use. Starting with jqGrid 4.7 one can define template in colModel with string value (see the pull request). In the way you will have the main information in colModel which can be serialized using JSON.stringify.

Reloading of data in JQgrid on button click is not working

I have successfully loaded data in my grid. I have enabled cell edit and on clicking a cell it will be in edit mode and multiple cells can be edited. The edited data will be stored later on clicking a custom update button. On clicking another custom button a new row will be added to the grid and that also will be saved on clicking the update button previously mentioned.
Now the problem is when I am trying to reset the edited values(ie. the edited cell values and the new row added before saving) using "reload" functionality nothing happens in the grid.It remains as same with the edited values and the empty new row...
My code is here
$scope.init = function() {
var grid = $("#list");
var lastSel, dataSel, dataLen;
var colD, colM, colN, userdata;
jQuery.ajax({
async: false,
type: "GET",
url:"getData.htm",
data: "",
dataType: "json",
success: function(result){
colD = result.colData,
colM = result.colModel,
colN = result.colNames,
userdata = colD.userdata;
jQuery("#list").jqGrid({
datatype: 'local',
data: colD.rootVar,
colModel:colM,
sortorder: 'asc',
viewrecords: true,
resizable: true,
gridview: true,
altRows: true,
cellEdit:true,
footerrow: true,
scrollbar: true,
overflow: scroll,
scrollrows: true,
loadonce:true,
autowidth: true,
shrinkToFit: false,
editurl: 'clientArray',
cellsubmit: 'clientArray',
afterEditCell: function (id,name,val,iRow,iCol){
},
afterSaveCell : function(rowid,name,val,iRow,iCol) {
var updtd = jQuery("#list").jqGrid('getCol', name, false, 'sum');
var objs = [];
objs[name] = updtd;
jQuery("#list").jqGrid('footerData','set',objs);
},
loadComplete: function(data){
jQuery("#list").jqGrid('footerData','set',{'Employer':'Max Guest Count:'});
var colnames = jQuery("#list").jqGrid ('getGridParam', 'colModel');
dataLen = colnames.length;
dataSel = colnames[3]['name'];
for (var i = 3; i < colnames.length; i++){
var tot = jQuery("#list").jqGrid('getCol', colnames[i]['name'], false, 'sum');
var ob = [];
ob[colnames[i]['name']] = tot;
jQuery("#list").jqGrid('footerData','set',ob);
}
var ids = grid.getDataIDs();
for (var i = 0; i < ids.length; i++) {
grid.setRowData ( ids[i], false, {height: 25} );
}
jQuery ("table.ui-jqgrid-htable", jQuery("#list")).css ("height", 30);
},
gridComplete: function () {
jQuery("#list").jqGrid('setColProp','id',{width:20});
jQuery("#list").jqGrid('setColProp','Employer',{width:80});
jQuery("#list").jqGrid('setColProp','Sponsor',{width:80});
var tabs = $("#tabs");
var width = tabs.width();
jQuery("#list").jqGrid('setGridWidth', width - 80, true);
jQuery("#list").jqGrid('setGridHeight', 270);
},
});
},
});
jQuery("#list").jqGrid('setGroupHeaders', {
useColSpanStyle: true,
groupHeaders:[
{startColumnName: 'id', numberOfColumns: 1, titleText: ''},
{startColumnName: 'Employer', numberOfColumns: 2, titleText: ''},
{startColumnName: dataSel, numberOfColumns: dataLen, titleText: '<Strong><font color="white">Here Comes</font></Strong>'}
]
});
$("#addtn").click(function(){
var newRowData = {"Id":"","Employer":"","Sponsor":"",col1:"",col2:"",col3:"",col4:"",col5:"",col6:"",col7:"",col8:"",col9:"",col10:"",col11:"",col12:"",col13:"",col14:"",col15:"",col16:"",col17:"",col18:"",col19:"",col20:""};
jQuery("#list").addRowData(0,newRowData,"first",1);
jQuery("#list").editRow(0,true);
});
$("#rstbtn").click(function(){
$("#list").jqGrid('setGridParam',{datatype:'json', page:1, current:true}).trigger('reloadGrid')
});
};
I will really appreciate if someone can advice on this..
Probably because of this line: loadonce:true, in jqgrid definition. Set it as false and try again.
And for reloading, try this code:
$( '#list' ).trigger( 'reloadGrid', [{ page: 1}] );
Below code worked for me, to load updated data from the array.
$('#grid').jqGrid('clearGridData');
$("#grid").jqGrid('setGridParam',{data: DataArr, datatype:'local'}).trigger('reloadGrid');

kendo ui grid filtering, pager not updated

i have encountered a problem on filtering in kendo 2012.3.1315.340 grid filtering, i have textboxes on the header template for filter function, once i filter, my paging is not working properly, i get proper data but my page count and total records don't change on the UI
Here is my code..
function searchOnFilters(element) {
var filtersModel = getSearchFilters();
//debugger;
var filterResults = new kendo.data.DataSource({
serverPaging: true,
serverSorting: true,
serverFiltering: true,
batch: true,
pageSize: 50,
transport: {
read: {
url: '#Url.Action("MasterQA_Read", "MasterQA")',
data: { searchFilters: JSON.stringify(filtersModel) },
type: "POST"
}
},
parameterMap: function (data, operation) {
return kendo.stringify(data);
},
schema: {
data: "Data",
total : "Total"
}
});
filterResults.fetch(function () {
// debugger;
var grid = $("#MQASearchGrid").data("kendoGrid");
grid.dataSource = filterResults;
grid.refresh();
});
}
Controller:
var result1 = new DataSourceResult
{
Data = gridData.Items,
Total = gridData.TotalCount
};
return Json(result1, JsonRequestBehavior.AllowGet);
Try using the setDataSource method of the grid. Assigning the dataSource field has no effect.

Resources