add new row to empty kendo grid - javascript

I have this grid
$("#email-grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "operations/get_emails_sales_reps.php?salesRepsId=" + salesRepsId,
type: "GET"
},
update: {
url: "operations/edit_email.php?salesRepsId=" + salesRepsId,
type: "POST",
complete: function (e) {
$("#email-grid").data("kendoGrid").dataSource.read();
}
},
destroy: {
url: "operations/delete_email.php",
type: "POST",
complete: function (e) {
$("#email-grid").data("kendoGrid").dataSource.read();
}
},
create: {
url: "operations/add_email.php?salesRepsId=" + salesRepsId,
type: "POST",
complete: function (e) {
$("#email-grid").data("kendoGrid").dataSource.read();
}
},
},
schema: {
data: "data",
total: "data.length", //total amount of records
model: {
id: "SalesRepId",
fields: {
EmailType: {
defaultValue: {
EmailTypeId: 2,
EmailTypeName: "Home"
}
},
EmailText: {
type: "string"
},
IsMainEmail: {
type: "boolean"
}
}
}
},
pageSize: 5,
},
height: 250,
filterable: true,
sortable: true,
pageable: true,
reorderable: false,
groupable: false,
batch: true,
navigatable: true,
toolbar: ["create", "save", "cancel"],
editable: true,
columns: [{
field: "EmailType",
title: "Type",
editor: EmailTypeDropDownEditor,
template: "#=EmailType.EmailTypeName#"
}, {
field: "EmailText",
title: "Email",
}, {
field: "IsMainEmail",
title: "Main?",
width: 65,
template: function (e) {
if (e.IsMainEmail == true) {
return '<img align="center" src ="images/check-icon.png" />';
} else {
return '';
}
}
// hidden: true
}, {
command: "destroy",
title: " ",
width: 90
},
]
});
the code in the server side (get_emails_sales_reps.php)
<?php
require_once ("../lib/salesrep.php");
require_once ("../lib/helper.php");
// add the header line to specify that the content type is JSON
header("Content-type: application/json");
$options = array();
$result = SalesRep::getRepEmails($_GET["salesRepsId"]);
if (isset($result) && $result != null) {
$result = _object_to_array($result);
if (isset($result[0]) && is_array($result)) {
for ($i = 0; $i < count($result); $i++) {
$result[$i]["EmailType"] = array("EmailTypeName" => $result[$i]["EmailType"], "EmailTypeId" => $result[$i]["EmailTypeId"]);
}
} else {
$result["EmailType"] = array("EmailTypeName" => $result["EmailType"], "EmailTypeId" => $result["EmailTypeId"]);
}
if (isset($result) || $result != null) {
echo "{\"data\":" . json_encode($result) . "}";
} else {
echo "{\"data\": {} }";
}
}
?>
when the grid has one record or more, I can add new record without any errors, but when there are no records the grid and try to add a new record. I get this error
Uncaught TypeError: Cannot read property 'length' of undefined
please, how can I fix this ??

I've solved this issue by editing the php file. when result is null ( empty) I have to return an empty json array like this
else {
// the result is null
echo "{\"data\": [] }";
}

Related

How to set cutom template for kendo grid columns

I need to set Kendo grid action button Icon based on value. My code as follows,
function InitProductServicesGrid() {
var prodServiceDataSource = new kendo.data.DataSource({
transport: {
type: "json",
read:
{
url: SERVER_PATH + "/LTSService/ProductsService.asmx/GetProductServiceDetailsList",
type: "POST",
contentType: 'application/json',
data: GetAdditonalData,
datatype: "json"
},
update:
{
url: SERVER_PATH + "/LTSService/ProductsService.asmx/SaveProductService",
type: "POST",
contentType: 'application/json',
datatype: "json"
}
},
schema: {
data: function (result) {
return JSON.parse(result.d);
},
model: {
id: "Id",
fields: {
Id: { type: "int" },
ServiceTime: { type: "string" },
IsActive: { type: "boolean"}
}
}
},
requestEnd: function (e) {
if (e.type === "destroy") {
var grid = $("#productServicesGrid").data("kendoGrid");
grid.dataSource.read();
}
},
error: function (e) {
e.preventDefault();
if (e.xhr !== undefined && e.xhr !== null) {
var messageBody = e.xhr.responseJSON.Message;
ShowGritterMessage("Errors", messageBody, false, '../App_Themes/Default/LtsImages/errorMessageIcon_large.png');
var grid = $("#productServicesGrid").data("kendoGrid");
grid.cancelChanges();
}
},
pageSize: 20,
});
$("#productServicesGrid").kendoGrid({
dataSource: prodServiceDataSource,
sortable: true,
filterable: false,
pageable: true,
dataBound: gridDataBound,
editable: {
mode: "inline",
confirmation: false
},
columns: [
{ field: "Id", title: "", hidden: true },
{
field: "ServiceTime",
title: "Time Standard",
sortable: false,
editor: function (container, options) {
var serviceTimeTxtBox = RenderServiceTime();
$(serviceTimeTxtBox).appendTo(container);
},
headerTemplate: '<a class="k-link" href="#" title="Time Standard">Time Standard</a>'
},
{
title: "Action", command: [
{
name: "hideRow",
click: hideRow,
template: comandTemplate
}
],
width: "150px"
}
]
});
}
I wrote a custom template function as follows,
function comandTemplate(model) {
if (model.IsActive == true) {
return '<a title="Hide" class="k-grid-hideRow k-button"><span class="k-icon k-i-lock"></span></a><a title="Hide"></a>';
}
else {
return '<a title="Show" class="k-grid-hideRow k-button"><span class="k-icon k-i-unlock"></span></a><a title="Show"></a>';
}
}
But when I debug the I saw the following value for model value.
I followed this sample code as well. here you can see, I also set the custom template like the sample code. Please help me to solve this. Why I can't access model IsActive value from comandTemplate function.
Updated
When clicking hideRow action, I access the dataItem as follows.
function hideRow(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
if (dataItem.IsActive == true) {
dataItem.IsActive = false;
}
else {
dataItem.IsActive = true;
}
}
Is there any possible way to access data from template function as above or any other way?
I would suggest a different approach because you can't access grid data while rendering and populating grid.
My suggestion is to use two actions and hide it based on the flag (in your case IsActive).
Something like this: Custom command
NOTE: in visible function you can access item!
EDIT: you can access it and change it on dataBound traversing through all data.
Check this example: Data bound
I don't see the advantage of relying on the grid commands. You can render any button you want yourself and and use the dataBound event to bind a click handler:
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{
template: function(dataItem) {
const isActive = dataItem.isActive;
return `<a title=${isActive ? "Hide": "Show"} class="k-grid-hideRow k-button"><span class="k-icon k-i-${isActive ? 'lock' : 'unlock'}"></span></a>`
}
}
],
dataBound: function(e) {
e.sender.tbody.find(".k-grid-hideRow").click(evt => {
const row = evt.target.closest("tr")
const dataItem = e.sender.dataItem(row)
dataItem.set("isActive", !dataItem.isActive)
})
},
dataSource: [{ name: "Jane Doe", isActive: false }, { name: "Jane Doe", isActive: true }]
});
Runnable Dojo: https://dojo.telerik.com/#GaloisGirl/eTiyeCiJ

Error TS2339: Property 'Default' does not exist on type 'string'.**

I am new to Angular 2
- My functionality is working fine in fiddle but when I put in the code base I am getting below errors.
app/components/playing-cables/-update.ts(82,12): error TS2339: Property 'options' does not exist on type 'jQuery'.
app/components/playing-cables/-update.ts(99,21): error TS2339: Property 'Default' does not exist on type 'string'.
storedPreferences.Default = {
dropdown.options = function(data, selectedKey) {
Can you tell me how to fix it.
Providing my code below.
Working code http://jsfiddle.net/yk0up9ht/
import {Component, ElementRef, Inject, OnInit,ViewChild} from '#angular/core';
import { sportService } from '../../services/sport.service';
import {playesRightBarMultiTabComponent} from '../playing-sports/playes-right-bar-multi-tab'
import {playerComponent} from '../player/player.component';
import {ProgressCircle} from '../shared/progress/progress-circle';
import {playeService} from '../../services/playeService';
import {playingsportsEvergreen} from '../playing-sports/playe-sports-evergreen';
import {TextDecoder} from 'text-encoding-shim';
import { Router} from '#angular/router';
import {NetworkCarousel} from '../shared/content/network-carousel';
import {KendoGridComponent} from '../grid/grid.component';
import { TranslateService } from '../../translate/translate.service';
//import { ProgressCircle } from '../shared/progress/progress-circle';
#Component({
selector: 'downlinkBulkUpdate',
templateUrl: "./app/components/playing-cables/downlink-bulk-update.html",
})
export class downlinkBulkUpdate {
public dataSourceVal;
public selectedRowsUID = [];
private count: boolean = true;
private selectAll: boolean;
#ViewChild(KendoGridComponent) private gridkendo: KendoGridComponent;
constructor(public elementRef: ElementRef,private router: Router){
}
private kendocommand = {
edit: { createAt: "bottom" },
group: false,
reorder: true,
resize: true,
sort: true,
filter: { mode: "row,menu" },
autoBind: false,
pager: { messages: { display: "Showing {0} to {1} of {2} entries" } },
model: {},
columns: [],
pagesize: 50,
getComponentUrl: "admin/v1/lockedItems",
saveStatus: false,
excelfileUidName: "ViewUnlockExport",
excelFileName: {
fileName: "ViewUnlockExport",
allPages: true
},
change: function (e) {
console.log("kendocommand downlink-bulk-update");
$('tr').find('[type=checkbox]').prop('checked', false);
$('tr.k-state-selected').find('[type=checkbox]').prop('checked', true);
},
searchFields: []
};
ngOnInit() {
$("tr th[data-field='codeLong']").hide();
if ($('input.checkbox_check').prop('checked')) {
//blah blah
alert("checked");
$("tr th[data-field='codeLong']").show();
}
$("#win1").hide();
/*document.getElementById('cars').options[0].text = localStorage.getItem("someVarName") || 'unkonwn';
var dropdown = $('<select>');
alert("I am here dropdownmenu select"); */
var dropdown = $('#cars');
dropdown.options = function(data, selectedKey) {
var self = this;
var newOptions = '<option value="Default">Default</option>'; //create one objec to save new options
$.each(data, function(ix, val) {
var selected = (val == selectedKey) ? 'selected="selected"' : '';
if (val != 'Default') {
newOptions += '<option value="' + val + '" ' + selected + '>' + val + '</option>';
}
//data.push(option);
});
self.html(newOptions);
self.change();
}
//var array = ['one', 'two', 'three'];
var array = [];
var storedPreferences = localStorage.getItem('preferences');
storedPreferences = (storedPreferences) ? JSON.parse(storedPreferences) : {};
storedPreferences.Default = {
columns: [0,1,2],
};
for (var storedPreference in storedPreferences) {
array.push(storedPreference);
}
dropdown.options(array, 'Default');
//$('body').append(dropdown);
$('#btnSubmit').on('click', function(ix, val) {
//should clear out the current options
//and replace with the new array
alert("I am here dropdownmenu");
var newArray = ['four', 'five', 'six'];
dropdown.options(newArray, 'Default');
});
$("#open1").click(function() {
alert("I am here");
$("#win1").show().kendoWindow({
width: "300px",
height: "500px",
modal: true,
title: "Window 1"
});
$("#win1").data("kendoWindow").open();
});
$("#clearPrefrence").click(function() {
alert("clearPrefrence");
//localStorage.clear();
//$("#cars option[value=volvo]").remove();
if ($('#cars').val() != 'Default') {
var preferences = localStorage.getItem('preferences');
if (preferences) {
preferences = JSON.parse(preferences);
}
else {
preferences = {};
}
delete preferences[$('#cars').val()];
localStorage.setItem('preferences', JSON.stringify(preferences));
$("#cars option:selected").remove();
$("#cars").change();
}
});
$("#win1Submit").click(function() {
var testingMickey = $("#mickey").val();
alert("win1Submit I am here--->" + testingMickey);
//document.getElementById('cars').options[0].text = testingMickey;
var someVarName = testingMickey;
var preferences = localStorage.getItem('preferences');
if (preferences) {
preferences = JSON.parse(preferences);
}
else {
preferences = {};
}
var preference = {
columns: [],
}
$('#rmenu input[type=checkbox]:checked').each(function() {
preference.columns.push($(this).data('index'));
});
preferences[testingMickey] = preference;
localStorage.setItem('preferences', JSON.stringify(preferences));
var getItemsomeVarName1 = localStorage.getItem('preferences');
getItemsomeVarName1 = JSON.parse(getItemsomeVarName1);
var optionArray = [];
for (var key in getItemsomeVarName1) {
optionArray.push(key);
}
alert("getItemsomeVarName1 I am here--->" + getItemsomeVarName1[testingMickey].columns.length);
dropdown.options(optionArray, testingMickey);
$("#win1").data("kendoWindow").close();
});
setGrid();
function toggleColumns() {
$('#rmenu input[type=checkbox]').each(function(index) {
$(this).data('index', index);
$(this).attr('data-index', index);
});
$('#rmenu input[type=checkbox]').change(function() {
var index = $(this).data('index') + 1;
if ($(this).is(':checked')) {
$('.k-grid-header-wrap > table tr th:nth-child(' + index + '),table.k-focusable tr td:nth-child(' + index + ')').show();
}
else {
$('.k-grid-header-wrap > table tr th:nth-child(' + index + '),table.k-focusable tr td:nth-child(' + index + ')').hide();
}
});
$('select').change(function() {
$('#rmenu input[type=checkbox]').removeAttr('checked').prop('checked', false);
var preferences = localStorage.getItem('preferences');
preferences = (preferences) ? JSON.parse(preferences) : {};
var columns = [0,1,2];
var key = $(this).val();
if (preferences && preferences[key]) {
columns = preferences[key].columns;
}
for (var a = 0; a < columns.length; a++) {
$('#rmenu input[type=checkbox][data-index=' + a + ']').prop('checked', true).attr('checked', 'checked');
}
$('#rmenu input[type=checkbox]').each(function() {
$(this).change();
});
});
}
toggleColumns();
$('.k-grid-header').on('contextmenu', function(e) {
e.preventDefault();
let menu = document.getElementById("rmenu");
menu.style.top = e.clientY + 'px';
menu.style.left = e.clientX + 'px';
menu.className = "show";
});
$(document).bind("click", function(event) {
document.getElementById("rmenu").className = "hide";
});
function setGrid() {
var ds1 = new kendo.data.DataSource({
transport: {
read: {
//using jsfiddle echo service to simulate JSON endpoint
url: "/echo/json/",
dataType: "json",
type: "POST",
data: {
// /echo/json/ echoes the JSON which you pass as an argument
json: JSON.stringify({
"country": [{
"codeLong": "AUT",
"codeShort": "AT",
"name": "Austria"
},
{
"codeLong": "BEL",
"codeShort": "BE",
"name": "Belgium"
},
{
"codeLong": "BGR",
"codeShort": "BG",
"name": "Bulgaria"
}
]
})
}
}
},
schema: {
data: "country",
model: {
fields: {
codeLong: {
type: "string"
},
codeShort: {
type: "string"
},
name: {
type: "string"
}
}
}
}
});
$("#grid1").kendoGrid({
dataSource: ds1,
height: 180,
scrollable: {
virtual: true
},
columns: [{
field: "codeLong",
title: "codeLong"
},
{
field: "codeShort",
title: "codeShort"
},
{
field: "name",
title: "name"
}
]
});
}
alert("downlink-bulk-update");
console.log("downlink-bulk-update");
let that = this;
$(document).ready(function(){
$(".showHideIcon").click(function(){
alert("titleSearchResults");
});
});
this.kendocommand.model = {
id: "isSelected",
fields: {
contextRow: { editable: false },
isSelected: { type: "boolean", editable: true, filterable: false },
moduleName: { type: "string", editable: false },
entityId: { type: "string", filterable: true, editable: false, nullable: false },
entityName: { type: "string", editable: false, nullable: true },
network: { type: "string", editable: false },
entityType: { type: "string", editable: false },
userLocked: { type: "string", editable: false },
additionalComments: { type: "string", editable: false },
checkOutDate: { editable: false }
}
};
this.kendocommand.columns = [
{
field: 'contextRow',
width: 25, locked: true
},
{
field: "isSelected", filterable: false, sortable: false, editable: true, title: "Is Selected",
template: function (container) { return that.checkboxchecker(container, "isSelected") },
width: 30,
headerTemplate: '<span class="displayBlock"><input type="checkbox" id="unlockCheck" /></span>'
},
{
field: "moduleName",
title: "Module Name", filterable: that.gridkendo.getAutoFilterName("contains", "moduleName"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function moduleName(options) {
console.log("downlink-bulk-update 2");
return that.gridTemplate(options, "moduleName", false);
},
width: 150
}, {
field: "entityId", title: "ID",
filterable: that.gridkendo.getAutoFilterName("eq", "entityId"),
headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function entityId(options) {
console.log("ending this.kendocommand.columns");
return that.gridTemplate(options, "entityId", false);
},
width: 90
}, {
field: "entityName", filterable: that.gridkendo.getAutoFilterName("contains", "entityName"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function entityName(options) {
return that.gridTemplate(options, "entityName", false);
},
title: "Name",
width: 150
}, {
field: "network",
title: "Network",
filterable: that.gridkendo.getAutoFilterName("contains", "network"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function networkName(options) {
return that.gridTemplate(options, "network", false);
},
width: 110
}, {
field: "entityType",
title: "Type", filterable: that.gridkendo.getAutoFilterName("contains", "entityType"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function entityType(options) {
return that.gridTemplate(options, "entityType", false);
},
width: 150
}, {
field: "userLocked",
title: "User Locked", filterable: that.gridkendo.getAutoFilterName("contains", "userLocked"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function userLocked(options) {
return that.gridTemplate(options, "userLocked", false);
},
width: 150
}, {
field: "additionalComments",
title: "Additional Comments bulk", filterable: that.gridkendo.getAutoFilterName("contains", "additionalComments"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function additionalComments(options) {
return that.gridTemplate(options, "additionalComments", false);
},
width: 200
}, {
field: "checkOutDate",
title: "Date Checked Out", filterable: that.gridkendo.getAutoFilterName("contains", "checkOutDate"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function checkOutDate(options) {
return that.gridTemplate(options, "checkOutDate", false);
},
width: 200
}
];
console.log("ending this.kendocommand.columns");
}
private gridTemplate(options: any, fieldName: any, mandatory: any) {
console.log("gridTemplate downlink-bulk-update");
let value = options[fieldName];
if (options[fieldName] == null || options[fieldName] == undefined) {
value = "";
options[fieldName] = " ";
}
options[fieldName + "FilterRowId"] = value;
return value;
}
checkboxchecker(container, fieldName: any): any {
console.log("checkboxchecker downlink-bulk-update");
if ((this.selectedRowsUID.indexOf(container.uid) != -1) || this.selectAll) {
container.isSelected = true;
return '<input type="checkbox" checked="checked" style="display:block;" class="textAligncenter unlockCheckbox" #= fieldName ? \'checked="checked"\' : "false" #= fieldName/>';
} else {
this.count = true;
container.isSelected = false;
return '<input type="checkbox" style="display:block;" class="textAligncenter unlockCheckbox" #= fieldName ? \'checked="checked"\' : "false" #= fieldName/>';
}
}
}
‌
I suppose the 'options' problems occurs here:
var dropdown = $('#cars');
dropdown.options = function(data, selectedKey) ...
Well, this works in JavaScript, but the error the TypeScript compiler gives you is due to static type-checking. dropdown is here a jQuery object, and that type (assuming you're using type definitions for jQuery) does not declare a options property, so assigning to it generates an error. To allow TypeScript to do this, you must typecast to any, so the object behaves like any JavaScript object:
var dropdown: any = $('#cars');
dropdown.options = (...)
In the case of .Default it is the same error: you are declaring storedPreferences as
var storedPreferences = localStorage.getItem(...);
TypeScript knows that localStorage.getItem returns a string, so it considers storedPreferences to be of type string. In TypeScript you cannot change the type of a variable. In fact, it's the kind of thing it has been designed to prevent (as it is common in JavaScript and cause of frequent errors). TypeScript knows that string does not have a Default property and indicates an error.
To avoid this, again, you must declare storedPreferences to be of type any:
let storedPreferences: any = localStorage.getItem(...);
The problem is that you're programming in TypeScript as if it were JavaScript, and that's why you're getting compiler errors. In TypeScript you cannot add new properties to an object of a known type. To do this, you must previously declare the object as any, so TypeScript behaves exactly like JavaScript (though this way you lose TypeScript advantages).
Besides all this, you should avoid using var and use let or const instead.
The code in jsfiddle works, because that is JavaScript code, not TypeScript code.

Kendo treelist Child node issue

whenever i cancelled the updating process from the child node,the child node just merge with root node,i don't find error in the console or i can't find anything suspicious.but after a reload,all becomes normal
$(document).ready(function () {
var windowTemplate = kendo.template($("#windowTemplate").html());
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: "officeprofiletree",
type: 'POST',
dataType: "json"
},
update: {
url: "officeprofilenametree_update",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
destroy: {
url: "officeprofilenametree_destroy",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models)
{
return JSON.stringify(options.models);
}
}
},
batch: true,
sort: { field: "name", dir: "asc" },
schema: {
model: {
id: "officeProfileNMId",
parentId: "parentId",
fields: {
officeProfileNMId: { type:"number" },
parentId:{nullable:true,type:"number"},
mobile:{ type:"string"},
address:{type:"string"},
phone: {type:"string"},
},
}
}
});
var window = $("#window").kendoWindow({
visible:false,
title: "Are you sure you want to delete this record?",
width: "450px",
height: "60px",
}).data("kendoWindow");
var treelist = $("#treelist").kendoTreeList({
dataSource: dataSource,
pageable: true,
dataBound: function (){
var tree = this;
var trs = this.tbody.find('tr').each(function(){
var item = tree.dataItem($(this));
if( item.parentId == null) {
$(this).find('.k-button,.k-button').hide();
}
});
},
columns: [
{ field: "name", title: "Name"},
{ field: "mobile", title:"Mobile", format: "{0:c}", hidden: true },
{ field: "address", title:"Address",hidden: true },
{ field: "phone",title:"Phone" ,hidden: true },
{ command: [
{name: "edit"},
{name: "Delete",
click: function(e){
e.preventDefault();
var tr = $(e.target).closest("tr");
var data = this.dataItem(tr);
window.content(windowTemplate(data));
window.center().open();
$("#yesButton").click(function(){
treelist.dataSource.remove(data);
treelist.dataSource.sync();
window.close();
reloading();
})
$("#noButton").click(function(){
window.close();
})
}
}
]}
] ,
editable: {
mode: "popup",
},
}).data("kendoTreeList");
});
the updation and deletion works fine by the way,Here is the fiddle
https://jsfiddle.net/me09jLy7/2/
updation:
whenever i create a child to ranikannur gives me 3 children with same name in each root ranikannur,in my database there is only one child is parented by ranikannur but treelist shows it as 3 children in each parent node,the children count 3 is getting from the total ranikannurparent nodes(here tree has 3 ranikannur parent nodes)
i guess.how is this getting the 3 children?
u just try it...
$(document).ready(function () {
var windowTemplate = kendo.template($("#windowTemplate").html());
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: "officeprofiletree",
type: 'POST',
dataType: "json"
},
update: {
url: "officeprofilenametree_update",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
destroy: {
url: "officeprofilenametree_destroy",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models)
{
return JSON.stringify(options.models);
}
}
},
batch: true,
sort: { field: "name", dir: "asc" },
schema: {
model: {
id: "officeProfileNMId",
parentId: "parentId",
fields: {
officeProfileNMId: { type:"number" },
parentId:{nullable:true,type:"number"},
mobile:{ type:"string"},
address:{type:"string"},
phone: {type:"string"},
},
}
}
});
var window = $("#window").kendoWindow({
visible:false,
title: "Are you sure you want to delete this record?",
width: "450px",
height: "60px",
}).data("kendoWindow");
var treelist = $("#treelist").kendoTreeList({
dataSource: dataSource,
pageable: true,
dataBound: function (){
var tree = this;
var trs = this.tbody.find('tr').each(function(){
var item = tree.dataItem($(this));
if( item.parentId == null) {
$(this).find('.k-button,.k-button').hide();
}
});
},
columns: [
{ field: "name", title: "Name"},
{ field: "mobile", title:"Mobile", format: "{0:c}", hidden: true },
{ field: "address", title:"Address",hidden: true },
{ field: "phone",title:"Phone" ,hidden: true },
{ command: [
{name: "edit"},
{name: "Delete",
click: function(e){
e.preventDefault();
var tr = $(e.target).closest("tr");
var data = this.dataItem(tr);
window.content(windowTemplate(data));
window.center().open();
$("#yesButton").click(function(){
treelist.dataSource.remove(data);
treelist.dataSource.sync();
window.close();
reloading();
})
$("#noButton").click(function(){
window.close();
})
}
}
]}
] ,
editable: {
mode: "popup",
},
}).data("kendoTreeList");
});

Kendo Grid - How to make grid displayed grouped data by one column by default (init)?

i would like to display grouped data in grid by default?
Should I do it during the read method?
Many Thanks for any help.
Edit:
Model filed for the object what i want to use for default grouping is following:
partner: {
defaultValue: {},
nullable: false,
type: "object"
},
Column field is:
{
field :"partner.name",
title : $translate.instant('PARTNER'),
width: 250,
filterable: {
cell: {
operator: "contains"
}
}
},
If i tried following in requestEnd:
var grid = $("#locations_grid").data('kendoGrid');
grid._group = true;
grid.dataSource._group.push({
aggregates: [],
dir: "asc",
field: "partner.name"
});
grid.refresh();
I always get empty grid.
Request strtucture for grouping is following:
{
"entityName": "Location",
"data": {
"take": 10,
"skip": 0,
"page": 1,
"pageSize": 10,
"group": [
{
"field": "partner.name",
"dir": "asc",
"aggregates": []
}
]
}
}
EDIT2 - WHOLE CODE OF THE GRID INIT:
$scope.initGrid = function() {
// set container for loading spinner
gridView = $("#locations_grid");
// set all properties for data grid
gridView.kendoGrid({
dataSource: {
transport: {
// READ REQUEST
read: function (options) {
console.log("List");
console.log(options.data);
requestParams = {
"entityName": "Location"
};
requestParams.data = options.data;
console.log(requestParams);
ApiService.doHttpRequest(
"POST",
$rootScope.apiBaseUrl + "location/search",
requestParams
)
.success(function (data, status, headers, config) {
// successful data retrieval
console.log("request success, checking state");
console.log(data);
// sent status to global HTTP status service
var jsonResponse = ApiService.processReturnedHttpState(status);
console.log("Status response is " + jsonResponse.result);
// do something with data
switch (jsonResponse.result) {
case true:
options.success(data);
break;
case false:
growlNotifications.add($translate.instant('LIST_LOADING_ERROR'), 'error', $rootScope.notificationLifetime);
break;
}
})
.error(function (data, status, headers, config) {
var jsonResponse = ApiService.processReturnedHttpState(status);
console.log("Processing error with status " +status);
growlNotifications.add($translate.instant('PROCESSING_REQUEST_ERROR') + jsonResponse.message , 'error', $rootScope.notificationLifetime);
// hide loading spinner
kendo.ui.progress(gridView, false);
});
},
// UPDATE REQUEST
update: function (options) {
console.log("Update");
console.log(options.data);
// ADD DATA FOR UPDATE TO THE TOKEN
console.log(requestParams);
console.log(options.data);
requestParams = options.data;
ApiService.doHttpRequest(
"POST",
$rootScope.apiBaseUrl + "/location/update",
requestParams
)
.success(function (data, status, headers, config) {
// successful data retrieval
// successful data retrieval
console.log("request success, checking state");
console.log(data);
// sent status to global HTTP status service
var jsonResponse = ApiService.processReturnedHttpState(status);
console.log("Status response is " + jsonResponse.result);
// do something with data
switch (jsonResponse.result) {
case true:
growlNotifications.add($translate.instant('UPDATED'), 'success', $rootScope.notificationLifetime);
options.success(data);
break;
case false:
growlNotifications.add($translate.instant('LIST_LOADING_ERROR'), 'error', $rootScope.notificationLifetime);
break;
}
})
.error(function (data, status, headers, config) {
growlNotifications.add($translate.instant('PROCESSING_REQUEST_ERROR') + data , 'error', $rootScope.notificationLifetime);
});
},
// DELETE FUNCTION
destroy: function (options) {
console.log("delete");
console.log(options.data);
// add data to request params
console.log("delete id: " +options.data.id);
// call the service
ApiService.doHttpRequest(
"POST",
$rootScope.apiBaseUrl + "/location/delete",
requestParams)
.success(function (data, status, headers, config) {
// successful data retrieval
console.log("request success, checking state");
console.log(data);
// sent status to global HTTP status service
var jsonResponse = ApiService.processReturnedHttpState(status);
console.log("Status response is " + jsonResponse.result);
// do something with data
switch (jsonResponse.result) {
case true:
options.success(data);
break;
case false:
growlNotifications.add($translate.instant('LIST_LOADING_ERROR'), 'error', $rootScope.notificationLifetime);
break;
}
})
.error(function (data, status, headers, config) {
var jsonResponse = ApiService.processReturnedHttpState(status);
console.log("Processing error with status " +status);
growlNotifications.add($translate.instant('PROCESSING_REQUEST_ERROR') + jsonResponse.message , 'error', $rootScope.notificationLifetime);
// hide loading spinner
kendo.ui.progress(gridView, false);
});
},
// CREATE FUNCTION
create: function (options) {
console.log("Create");
console.log(options.data);
// ADD DATA FOR UPDATE TO THE TOKEN
requestParams = options.data;
ApiService.doHttpRequest(
"POST",
$rootScope.apiBaseUrl + "location/create",
requestParams
)
.success(function (data, status, headers, config) {
// successful data retrieval
console.log("request success, checking state");
console.log(data);
// sent status to global HTTP status service
var jsonResponse = ApiService.processReturnedHttpState(status);
console.log("Status response is " + jsonResponse.result);
// do something with data
switch (jsonResponse.result) {
case true:
options.success(data);
var dataSource = gridView.dataSource;
gridView.data('kendoGrid').dataSource.read();
growlNotifications.add($translate.instant('SUCCESSFULLY_ADDED'), 'success', $rootScope.notificationLifetime);
break;
case false:
growlNotifications.add($translate.instant('PROCESSING_ERROR'), 'error', $rootScope.notificationLifetime);
options.success(data);
break;
}
})
.error(function (data, status, headers, config) {
var jsonResponse = ApiService.processReturnedHttpState(status);
console.log("Processing error with status " +status);
growlNotifications.add($translate.instant('PROCESSING_REQUEST_ERROR') + jsonResponse.message , 'error', $rootScope.notificationLifetime);
// hide loading spinner
kendo.ui.progress(gridView, false);
});
}
},
requestStart: function(e) {
console.log("Request start");
// show loading spinner
//kendo.ui.progress(gridView, true);
},
requestEnd: function(e) {
console.log("Request end");
/*
if(e.type === "read"){
var grid = $("#locations_grid").data('kendoGrid');
grid._group = true;
grid.dataSource._group.push({
aggregates: [],
dir: "asc",
field: "code"
});
grid.refresh();
}
*/
var response = e.response;
var type = e.type;
console.log(type);
kendo.ui.progress(gridView, false);
},
requestError: function(e) {
console.log("Request error");
// hide loading spinner
kendo.ui.progress(gridView, false);
},
// SCHEMA FOR DATAGRID
schema: {
model: {
id: "id",
fields: {
id: {
editable: false,
nullable: true,
defaultValue: null,
type: "number"
},
partner: {
defaultValue: {},
nullable: false,
type: "object"
},
accessNote: {
editable: true,
nullable: true,
type: "string"
},
address: {
defaultValue: {},
nullable: false
},
bsc: {
editable: true,
nullable: true
},
code:{
editable: true,
nullable: false,
type: "string",
validation: {
required: true,
min: 1
}
},
indoorOutdoor:{
editable: true,
nullable: false,
type: "string",
validation: {
required: {
message: $translate.instant('FIELD_IS_REQUIRED')
}
}
},
siteId:{
editable: true,
nullable: false,
type: "string",
validation: {
required: {
message: $translate.instant('FIELD_IS_REQUIRED')
}
}
},
stationType:{
defaultValue: {},
nullable: false,
validation: {
required: {
message: $translate.instant('FIELD_IS_REQUIRED')
}
}
}
}
},
data: function(response) {
console.log(response.results);
return response.results;
},
total: function(response) {
console.log(response.resultCount);
return response.resultCount;
}
},
// definition for page sorting
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
serverGrouping: true,
},
editable:{
confirmation:true //remove delete confirm message
},
scrollable:true,
//window resizing hack
height: function () {
return GlobalHelperService.getWindowSize();
},
filterable: GridHelperService.filtersTranlations(),
sortable: true,
groupable : {
messages: {
empty : $translate.instant('DRAG_SELECTED_COLUMN_HEADER_HERE_TO_GROUP')
}
},
reorderable: true,
resizable: true,
//dataBound: resizeGrid, //callback when data are loaded
columnMenu: GridHelperService.getColumnMenu(),
pageable: GridHelperService.getBottomToolbar(),
messages:GridHelperService.getToolbarButtonsTranlations(),
toolbar: [
{ name: "create" },
{ name: "save" },
{ name: "cancel" }
],
columns: [
{
field :"partner.name",
title : $translate.instant('PARTNER'),
width: 250,
filterable: {
cell: {
operator: "contains"
}
}
},
{
field :"accessNote",
title : $translate.instant('ACCESS_NOTE'),
width: 250,
filterable: {
cell: {
operator: "contains"
}
}
},
{
field :"address.city",
title : $translate.instant('ADDRESS_CITY'),
width: 250,
editor: GlobalHelperService.getAddressCityListForAutocomplete,
filterable: {
cell: {
operator: "contains"
}
}
},
{
field :"address.latitude",
title : $translate.instant('ADDRESS_LAT'),
width: 250,
filterable: {
cell: {
operator: "contains"
}
}
},
{
field :"address.longtitude",
title : $translate.instant('ADDRESS_LON'),
width: 250,
template: function(dataItem) {
console.log("DATAITEM IS FOLLOWING:");
console.log(dataItem);
var html = "<div>"+dataItem.address.longtitude+"<a class=\"showOnMapBtn\" href=\"http://maps.google.com/maps?q="+dataItem.address.latitude+","+dataItem.address.longtitude+"&z=14&ll="+dataItem.address.latitude+","+dataItem.address.longtitude+"\" target=\"blank\">"+$translate.instant('MAP')+"</a></div>";
return html;
},
filterable: {
cell: {
operator: "contains"
}
}
},
{
field :"address.street",
title : $translate.instant('ADDRESS_STREET'),
width: 250,
editor: GlobalHelperService.getAddressStreetListForAutocomplete,
filterable: {
cell: {
operator: "contains"
}
}
},
{
field :"bsc",
title : $translate.instant('BSC'),
width: 250,
filterable: {
cell: {
operator: "contains"
}
}
},
{
field :"code",
title : $translate.instant('CODE'),
width: 250,
filterable: {
cell: {
operator: "contains"
}
}
},
{
field :"indoorOutdoor",
title : $translate.instant('INDOOR_OUTDOOR'),
editor: GlobalHelperService.locationTypeDropDownEditor,
template: function(dataItem) {
switch (dataItem.indoorOutdoor)
{
case "Indoor":
return "Indoor";
case "Outdoor":
return "Outdoor";
case "IndoorOutdoor":
return "Indoor & Outdoor";
default:
return "Zvolte";
}
},
width: 250,
filterable: {
cell: {
operator: "contains"
}
}
},
{
field :"siteId",
title : $translate.instant('SITE_ID'),
width: 250,
filterable: {
cell: {
operator: "contains"
}
}
},
{
field :"stationType.name",
title : $translate.instant('STATION_TYPE'),
editor: GlobalHelperService.getStationTypeListForAutocomplete,
width: 250,
filterable: {
cell: {
operator: "contains"
}
}
}
]
});
};
Should I do it during the read method?
Yes, I believe that is the best way. Here is the function to group after data read on 'CompanyName' field:
$("#grid").kendoGrid({
dataSource: {
requestEnd: function(e){
if(e.type === "read"){
var grid = $("#grid").data('kendoGrid');
grid._group = true;
grid.dataSource._group.push({
aggregates: [],
dir: "asc",
field: "CompanyName"
});
grid.refresh();
}
}
},
groupable: true,
columns: [{
field: "CompanyName"
...
}
],
...
});
Kendo dojo example: http://dojo.telerik.com/oRuwA
Remember that this functionality is not official supported and uses grid private field, so it can stop working after any future updating of Kendo.
Angular example:
$scope.initGrid = function() {
gridView = $("#locations_grid");
gridView.kendoGrid({
dataSource: {
requestEnd: function(e){
if(e.type === "read"){
gridView._group = true;
gridView.dataSource._group.push({
aggregates: [],
dir: "asc",
field: "CompanyName"
});
gridView.refresh();
}
}
...
}
...
});
};

Type Error when trying to preserve filter state - Kendo UI Grid

I'm working with Kendo UI's Grid and attempting to add some code which preserves the grid's filter/grouping/etc by way of a cookie. It works in the example, but not at all in my code.
Example: http://www.kendoui.com/code-library/web/grid/preserve-grid-state-in-a-cookie.aspx
My Code: http://jsfiddle.net/PwajE/
For whatever reason (I'm sure it's a simple one) I keep getting type errors. Two hours later... here I am.
As always, any help is appreciated.
#RRfive
<script>
var data = [{"name":"John Smith","email":"test#test.com","permission":"admin","costRate":"60","dt":"2013-02-02 10:26:29","memberID":"M0000001"},{"name":"Test Simple","email":"test#jones.com","permission":"user","costRate":"40","dt":"2013-02-02 00:00:00","memberID":"M0000002"}];
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
data: data,
//transport: {
// read: "assets/data/data.users.php",
//},
schema: {
data: function(result) {
return result.data || result;
},
total: function(result) {
var data = this.data(result);
return data ? data.length : 0;
},
model:{
id:"memberID",
fields:{
dt:{ type:"date" },
costRate:{ type:"number" }
}
}
},
pageSize: 10,
},
sortable: {
mode: "single",
allowUnsort: true,
},
pageable: {
input: true,
numeric: false
},
reorderable: true,
resizable: true,
filterable: {
extra:false,
operators: {
string:{
contains: "Contains",
}
}
},
columnMenu: false,
groupable: true,
dataBound: function(e){
var grid = this;
var dataSource = this.dataSource;
var state = kendo.stringify({
page: dataSource.page(),
pageSize: dataSource.pageSize(),
sort: dataSource.sort(),
group: dataSource.group(),
filter: dataSource.filter()
});
$.cookie("employeesState",state);
if($.cookie('empRows')){
$.each(JSON.parse($.cookie('empRows')),function(){
var item = dataSource.get(this);
var row = grid.tbody.find('[data-uid='+item.uid+']');
row.addClass('k-state-selected');
})
}
},
change:function(){
var grid = this;
var ids = grid.select().map(function(){
return grid.dataItem($(this)).Id
}).toArray();
$.cookie('empRows',JSON.stringify(ids));
},
columns: [
{ field: "name", title:"Name" },
{ field: "email", title:"Email/Username" },
{ field: "costRate", title:"Cost Rate (p/hr)", template: '#= kendo.toString(costRate, "c") #', },
{ field: "permission", title:"Permission", template: "#= (permission == 'admin') ? 'Administrator' : 'User' #" },
{ field: "dt", title:"Registered", template: '#= kendo.toString(dt,"d-M-yyyy") #' },
{ field: "memberID", title:" ", width: "83px", filterable: false, sortable: false, template: '<a class="k-button k-button-icontext k-grid-edit" href="manage_admin.php?form=editMember&ID=#= kendo.toString(memberID, "n2")#"><span class=\"k-icon k-edit\"></span>Edit</a>'},
]
});
var state = JSON.parse($.cookie("employeesState"));
if(state){
if(state.filter){
parseFilterDates(state.filter, grid.dataSource.options.schema.model.fields);
}
grid.dataSource.query(state);
}
else{
grid.dataSource.read();
}
});
function parseFilterDates(filter, fields){
if(filter.filters){
for(var i = 0; i < filter.filters.length; i++){
parseFilterDates(filter.filters[i], fields);
}
}
else{
if(fields[filter.field].type == "date"){
filter.value = kendo.parseDate(filter.value);
}
}
}
</script>
If you debug that fiddle you would see that the following line throws the error:
grid.dataSource.query(state);
The reason for this is that grid is not an instance of Kendo Grid but the div elemen with id='grid'. The fix is simple - initialize the grid variable prior to using it:
var grid = $("#grid").data('kendoGrid');
grid.dataSource.query(state);

Categories