I have a jsp page with button.
On clicking of the button, it creates a dojo grid dynamically.
After grid gets loaded, am iterating through the grid and if particular value is there, the whole row get selected.
I achieved it by using the below code, row gets selected, but am getting an error.
Error: "error: dojo.data.ItemFileReadStore: Invalid item argument"
Am using dojoX.grid.DataGrid(1.7)
Here is the code to create the dynamic grid:
var ioArgs = {
url: "./DynamicDBServlet",
content: { TABLE_NAME:tableName,WHERE_CONDN:condtn,COLUMNS:gridColumnName,ACTION:'select'},
handleAs: "json",
load: function(response) {
//alert(response["items"][0].USER_ID);
var tbl = document.getElementById(gridID);
//alert(tbl);
if(tbl) tbl.parentNode.removeChild(tbl);
var gridLayout = [];
var key;
colmn=gridColumnName.split(',');
var i=0;
while(i<colmn.length) {
if(colmn[i]=="STATUS"){
key = colmn[i];
gridLayout.push({
field: key,
name: displayName[i],
formatter:function(opvalue){
//alert(opvalue);
opvalue = parseInt(opvalue);
if(opvalue==1){
return "Executing";}
if(opvalue==2){
return "Suspended";}
if(opvalue==3){
return "Completed";}
if(opvalue==4){
return "Aborted";}
if(opvalue==5){
return "Error";}
if(opvalue==6){
return "Terminated";}},
width: '200px',
editable: false});
i++;
}if(colmn[i]=="PRIORITY"){
key = colmn[i];
gridLayout.push({
field: key,
name: displayName[i],
formatter:function(opvalue){
if(opvalue==1){
return "High";}
if(opvalue==8){
return "Normal";}
if(opvalue==15){
return "Low";}
},
width: '200px',
editable: false});
i++;
}if(colmn[i]=="PROCESS_METADATYPE"){
key = colmn[i];
gridLayout.push({
field: key,
name: displayName[i],
formatter:function(opvalue){
if(opvalue==4497){
return "Provisioning Sub Process";}
if(opvalue==4496){
return "Provisioning Loop";}
if(opvalue==4494){
return "Main Process";}
},
width: '200px',
editable: false});
i++;
}if(colmn[i]=="ORDER_TYPE"){
key = colmn[i];
gridLayout.push({
field: key,
name: displayName[i],
formatter:function(opvalue){
if(opvalue==4488){
return "Training Order";}
},
width: '200px',
editable: false});
i++;
}else{
key = colmn[i];
gridLayout.push({
field: key,
name: displayName[i],
width: '200px',
editable: false});
i++;
}
}
//alert(gridLayout);
var gridStore = new dojo.data.ItemFileWriteStore({
data: response
});
var dumm = dijit.byId('dynamicgrid'+tableName);
if(dumm) {
dumm.destroy();
}
var finderResponse = new dojox.grid.DataGrid({
id:"dynamicgrid"+tableName,
query: { },
store:gridStore,
structure: gridLayout,
selectionMode: "single"
}, document.createElement("div"));
dojo.byId(parentDiv).appendChild(finderResponse.domNode);
//var varb=dijit.byId("finderResponseGrid"+tableName);
//alert(varb);
//varb.layout.setColumnVisibility(0, false);
gbshowgridFlag = true;
finderResponse.startup();
//dijit.byId('dynamicgridCWPROCESS').focus.setFocusIndex(0);
try{
for( var i=0; i < dijit.byId('dynamicgridCWPROCESS').rowCount; i++){
var items = dijit.byId('dynamicgridCWPROCESS').getItem(i);
var value=dijit.byId('dynamicgridCWPROCESS').store.getValue(items,"PROCESS_ID");
if(value=="2507"){
dijit.byId('dynamicgridCWPROCESS').selection.setSelected(i,true);
}
}
if(defineDbl){
getProcessgrid();
}
}catch(e){
alert(e);
}
},
error: function(error) {
alert("An unexpected error occurred: " + error);
}
};
var deferred = dojo.xhrPost(ioArgs);
This code help me to select row in grid :
grid.selection.select(rowIndex);
In your case:
finderResponse.selection.select(rowIndex);
I hope this will solve your problem.
function selectRowByYourOwn(){
var row = null;
// you have to get is some have.. try onSelected='yourOwnFn', on your table tag or your div tag.
// function yourOwnFn(rowID){ row = rowID;}
grid.selection.clear();
grid.selection.setSelected(row, true);
grid.render();
}
Related
I have 2 SelectControl from a Wordpress Gutenberg Custom Block I'm trying to build. I don't use ES6. Only ES5 and no JSX.
The 2 SelectControl should work in the following way:
They fetch from REST WP Api the Post Types and all the Posts. What I want to achieve is when I select an item from SelectControl 1 (Post Types) , I get the related filtered Posts in SelectControl 2. All the posts and post types are preloaded in array at page load.
I'm able with the code below to successfully populate both controls with the REST Api, but when it comes to filter the second selectcontrol according the selected value from the firstcontrol it doesn't work. No errors.
onChange: function(value) {
selectedType = value;
}
The code above doesn't sort any effect. Also no errors. Cannot figure out what is wrong here
(function(wp) {
var registerBlockType = wp.blocks.registerBlockType;
var InspectorControls = wp.blockEditor.InspectorControls;
var PanelBody = wp.components.PanelBody;
var TextControl = wp.components.TextControl;
var ColorPalette = wp.components.ColorPalette;
var SelectControl = wp.components.SelectControl;
var Dashicon = wp.components.Dashicon;
var el = wp.element.createElement;
var withState = wp.compose.withState;
var __ = wp.i18n.__;
var options = [{
value: 0,
label: __('Select a Post...')
}];
var optionsfiltered = null;
var selectedType = '';
var posttypeOptions = [{
value: 0,
label: __('Select a Post Type...')
}];
wp.apiFetch({
path: '/custom/v1/all-posts'
}).then(function(posts) {
var optionsAppend = posts.map(function(post) {
return {
value: post.id,
label: post.title,
type: post.type
}
});
options = options.concat(optionsAppend);
optionsfiltered = options;
});
wp.apiFetch({
path: '/wp/v2/types'
}).then(function(posttypes) {
console.log(posttypes);
for (let [key, item] of Object.entries(posttypes)) {
posttypeOptions.push({
value: item.slug,
label: item.name
});
}
});
function TestControl(props) {
var attributes = props.attributes;
var setAttributes = props.setAttributes;
var setState = props.setState;
var inspectorControl = el(InspectorControls, {},
el('h4', {}, el('span', {}, "Select Value")),
el(SelectControl, {
label: "Select a Post Type",
value: attributes.selectedPost,
options: posttypeOptions,
style: {
fontSize: '10px'
},
onChange: function(value) {
selectedType = value;
}
}),
el(SelectControl, {
label: "Select a Post",
value: attributes.selectedPost,
options: optionsfiltered.filter(function(el) {
return el.type === selectedType;
}),
style: {
fontSize: '10px'
},
onChange: function(value) {
setAttributes({
url: value
});
}
})
);
return el('div', {
style: {
backgroundColor: attributes.color,
color: "#00ff00"
}
},
inspectorControl
);
}
registerBlockType('resorcedomain/resource-cards-block', {
title: __('Resource Cards'),
category: 'widgets',
icon: {
foreground: '#46aaf8',
src: 'store'
},
attributes: {
posts: {
type: 'string',
default: null
},
orders: {
type: 'string',
default: null
},
tagfilter: {
type: 'string',
default: null
}
},
edit: withState({})(TestControl),
save: function(props) {
return null;
}
});
})(window.wp);
I forgot that wordpress is not 100% react. So i had to use setAttributes method in the onChange method. Looks like setAttributes is similar to setState in React and makes the plugin UI to refresh and to reload my TestControl.
When TestControl reloads my optionsfiltered.filter works and the array get filtered according the selection.
I'm using an auto-run block where I re-execute the same mongo with a few session variables ! loop over those doc , construct an array of events then I call the addEventSource and refetchResources function which are pretty expensive computationally ! the fullcalendar becomes slow the more data ! on every action the auto-run block is rerun ! what in your in your opinion can be done to speed things up ? I thought about only re-rendering the delta elements but this doesn't cover the deletion and update .
calendar = $('#calendar').fullCalendar({
schedulerLicenseKey: Meteor.settings.public.fullCalendarLicenseKey,
now: new Date(),
editable: true, // enable draggable events
droppable: true, // this allows things to be dropped onto the calendar
aspectRatio: 1.8,
timezone:'local',
disableDragging: true,
displayEventTime: false,
selectable:true,
allDaySlot:true,
slotDuration:'24:00',
lazyFetching:true,
resourceLabelText: 'Employees',
nextDayThreshold:"12:00",
resources: function(callback) {
var tmp_obj = { usersSorting : { } };
tmp_obj.usersSorting["indexByLocation."+Session.get("locationId")] = 1;
var users = [];
var data = Meteor.users.find({
$or:[
{"profile.showInScheduler":{$exists:false}},
{"profile.showInScheduler":true}
],
assignedTo:{$in:[Session.get("locationId")]},
'locations._id':Session.get("locationId"),
"profile.companyId":Session.get("companyId")
},{sort : tmp_obj.usersSorting});
var arr = data.map(function(c) {
var employeeType = c.userSettings.employeeType;
var type = EmployeeType.findOne({_id:employeeType});
var img = Images.findOne({_id: c.picture});
var imgUrl = img ? img.url() : "/images/default-avatar.png";
c.name = c.name || "";
var totalHoursAllLocation = 0;
var totalHoursCurrentLocation = 0;
return {
id: c._id,
title: "t",
width:"2px"
};
});
callback(arr);
},
drop: function(date, jsEvent, ui, resourceId) {
},
eventResize: function( event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ) {
},
dayClick: function(date, jsEvent, view,res,res2) {
},
eventClick: function ( event, jsEvent, view ) {
}
}).data().fullCalendar;
/********************* reactive calendar *****************/
this.autorun(function() {
if(Session.get("activeUsers")) {
schedulerSubs = Meteor.subscribe("SchedulesByLocation", Session.get("companyId"), Session.get("locationId"), Session.get("activeUsers"), moment(Session.get("currentDate")).startOf('week').toDate(), moment(Session.get("currentDate")).startOf('week').add(2, "weeks").endOf('isoweek').add(1,"days").toDate());
}
const company = Companies.findOne({_id: Session.get("companyId")});
Session.set("loading", true);
let events = [];
let usersInLocation = Meteor.users.find({
assignedTo: {$in: [Session.get("locationId")]},
'locations._id': Session.get("locationId"),
"profile.companyId": Session.get("companyId")
}).fetch();
let userIds = _.map(usersInLocation, "_id");
userIds.push("temp" + Session.get("companyId") + Session.get("locationId"));
Session.set("activeUsers",userIds);
if(schedulerSubs && schedulerSubs.ready()) {
var data;
SchedulerEvts = Schedules.find({
uid: {$in: userIds},
locationId: Session.get("locationId"),
companyId: Session.get("companyId"),
start: {$gte: moment(Session.get("currentDate")).startOf('week').toDate()},
end: {$lte: moment(Session.get("currentDate")).add(2, "week").endOf('isoweek').toDate()}
}).fetch();
SchedulerEvts.forEach(function (evt) {
var event = null;
var color = "";
var oloc = "";
var attendance = null;
var locationName = "";
var id = evt._id;
event = {
id:id,
type : evt.type,
title: evt.name,
start: evt.start,
end: evt.end,
color:color,
resourceId: evt.uid,
locationName:locationName,
};
events.push(event);
});
if (calendar) {
calendar.removeEvents();
calendar.addEventSource(events);
calendar.refetchResources();
}
}
I have this app with fullcalendar and everything but the eventDataTransform works fine. The code is really large, so i will publish the relevant parts
$(document).ready(function () {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,basicDay',
},
allDaySlot: false,
nextDayThreshold: '00:00:00',
slotLabelFormat: 'h(:mm)a',
views: {
month: {
//para que no se pueda arrastrar en la vista month
droppable: false,
timeFormat: 'h(:mm)a',
showNonCurrentDates:true,
},
week: {
timeFormat: 'h:mm:ss a'
},
day: {
timeFormat: 'h:mm:ss a'
},
basicDay:{
droppable: false,
}
},
locale: getVarLocale(),
editable: true,
droppable: true,
slotDuration: '00:15:00',
eventDurationEditable:false,
eventDragStart:function( event, jsEvent, ui, view ) {
isDragging=true;
},
eventDragStop:function( event, jsEvent, ui, view ) {
isDragging=false;
},
dayClick: function (date, jsEvent, view) {
if(isValidDate(date)==false)
return false;
if (view.name === "month") {
$('#calendar').fullCalendar('gotoDate', date);
$('#calendar').fullCalendar('changeView', 'agendaDay');
}
},
eventOverlap: function (stillEvent, movingEvent) {
if(stillEvent.start.isSame(movingEvent.end)||stillEvent.end.isSame(movingEvent.start)){
return false;
}
if (movingEvent.type == tiposEventos.bloque){
if(isDragging==false)
performAlert(translationCal.noNestedBlock,'event');
return false;
}
if(movingEvent.overlaped==false){
if (stillEvent.type!=tiposEventos.bloque){
if(isDragging==false)
performAlert(translationCal.noOverlapAllowed,'block');
return false;}
}
if(movingEvent.start.isBefore(stillEvent.start)){
if(isDragging==false)
return false;
}
updateEvent(stillEvent, movingEvent,true);
return true;
function performAlert(msg,type){
var alerted = localStorage.getItem(type) || '';
if(alerted=='alerted')
return false;
localStorage.setItem(type,'alerted');
var e=Array();
e.push(msg);
addModalError('pm-modal-error',$translation.error, e);
}
},
eventDataTransform:function(eventData){
console.log(eventData);
},
eventSources:[
{
events: function (start, end, timezone, callback) {
var events = [];
var options = {};
options.data = {};
options.data.start=start.format('YYYY-MM-DD');
options.data.end=end.format('YYYY-MM-DD');
options.type = 'text/json'
options.method = 'POST';
options.url = Routing.generate('publication_all');
options.errorcallback = function (error) {
console.log(error);
}
options.successcallback = function (data) {
var parseData = JSON.parse(data);
$(parseData).each(function () {
var startTime = this.startTime;
startTime = (((startTime.date).split(' ')[1]).split('.'))[0];
var startObj = moment(startTime, 'HH:mm:ss');
var startDate = (this.startDate.date).split(' ')[0];
var startDate = moment(startDate, 'YYYY-MM-DD HH:mm:ss').utcOffset(+0000);
startDate.set({
'hour': startObj.get('hour'),
'minute': startObj.get('minute'),
'second': startObj.get('second')
});
var endTime = this.endTime;
endTime = (((endTime.date).split(' ')[1]).split('.'))[0];
var endObj = moment(endTime, 'HH:mm:ss');
var endDate = (this.endDate.date).split(' ')[0];
endDate = moment(endDate, 'YYYY-MM-DD HH:mm:ss').utcOffset(+0000);
endDate.set({
'hour': endObj.get('hour'),
'minute': endObj.get('minute'),
'second': endObj.get('second')
});
if(isValidDate(startDate)==true){
events.push(
{
title: this.title, // use the element's text as the event title
idRef: this.idRef,
type: this.type,
publicationId: this.idPub,
color: setColors(this.type,this.idRef),
overlaped: false,
overlaps: false,
parentBlock: this.parent,
start: startDate,
end: (startDate.diff(endDate)==0)?endDate.set({'second':endDate.get('second')+1}):endDate,
stick: true,
idRef: this.ref,
direct:-1,
allDay:false,
durationEditable:(this.type==tiposEventos.bloque||this.type==tiposEventos.patron||this.type==tiposEventos.sennal)?true:false
}
);
}
});
callback(events);
};
ajaxAccess(options);
}
}
],
});
});
The thing is, everything works fine, but the eventDataTransform always throws TypeError: input is undefined
out._id = input._id || (input.id === undefined ? '_fc' + eventGUID++ : input.id ...
I checked the docs and I am calling the event in the proper way. I dont know if the problem is related to the fact that my eventSource is an ajax function.
your function doesn't return anything.
the eventDataTransform function has to. At least you could test:
console.log(eventData);
return eventData;
I am using Gridstack with Knockout.js. I am using http://troolee.github.io/gridstack.js/demo/knockout.html to create Gridstack widgets. I added a Google map in one of these widgets. The map appears with a scroll bar. Also, I need to have some kind of heading, as it is in its present state. The main problem is that the dimension of the map is fixed and when I resize the widget, the map does not fit in the widget automatically. Here is my full code:
ko.components.register('dashboard-grid', {
viewModel: {
createViewModel: function (controller, componentInfo) {
var ViewModel = function (controller, componentInfo) {
var grid = null;
this.widgets = controller.widgets;
this.id = controller.id;
this.afterAddWidget = function (items) {
if (grid == null) {
grid = $(componentInfo.element).find('.grid-stack').gridstack({
auto: false,
animate: true
}).data('gridstack');
}
var item = _.find(items, function (i) { return i.nodeType == 1 });
grid.addWidget(item);
ko.utils.domNodeDisposal.addDisposeCallback(item, function () {
grid.removeWidget(item);
});
};
};
return new ViewModel(controller, componentInfo);
}
},
template:
[
'<div class="grid-stack" data-bind="foreach: {data: widgets, afterRender: afterAddWidget}">',
' <div class="grid-stack-item" data-bind="attr: {\'data-gs-x\': $data.x, \'data-gs-y\': $data.y, \'data-gs-width\': $data.width, \'data-gs-height\': $data.height, \'data-gs-auto-position\': $data.auto_position}">',
' <div class="grid-stack-item-content" >',
' <header style="background-color: green;"> ',
' <button data-bind="click: $root.deleteWidget">Delete me</button><br>',
' <label><strong data-bind="text: $root.ids"></strong></label>',
' </header>',
' <div data-bind="attr: {id: $root.ids}">',
' </div>',
' </div>',
' </div>',
'</div> '
].join('')
});
$(function () {
var ids;
var Controller = function () {
var self = this;
this.widgets = ko.observableArray([]);
this.id = ko.observable("google-map");
this.ids = "";
this.addNewWidget = function () {
this.ids = this.id(); // this.ids is used to give id to div elements
this.widgets.push({
x: 0,
y: 0,
width:4,
height:5,
auto_position: true,
});
// calling method to draw map
createWidget(this.ids);
return false;
};
this.deleteWidget = function (item) {
self.widgets.remove(item);
return false;
};
};
ko.applyBindings(new Controller());
});
function createWidget(id) {
var dataArray, latitude, longitude, speed;
// Load the Visualization API and the corechart package.
try {
google.charts.load('current', {'packages':['map', 'gauge']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
}
catch ( err ) {
//console.log(err);
}
function drawChart() {
latitude = Number(12.93213);
longitude = Number(77.695185);
var mapOptions = {
showTooltip: true,
showInfoWindow: true,
zoomLevel: 16, // range: 0-21 for "roadmap" map type
mapType: 'roadmap',
enableScrollWheel: true,
draggable: false,
};
var coordinates = "Latitude : " + latitude + "\nLongitude : "+ longitude;
var mapData = google.visualization.arrayToDataTable([
['Lat', 'Long', 'Name'],
[latitude, longitude, coordinates]
] );
try {
//var chart = new google.visualization.Gauge(document.getElementById('gauge'));
var map = new google.visualization.Map(document.getElementById(id));
map.draw(mapData, mapOptions);
}
catch (err) {
console.log(err);
}
} // drawChart() ends here
} // createWidgets() ends here
I have a Kendo UI grid and a Kendo UI Window on the same page. The window contains form elements for record insertion, a record being represented by a row in the grid. But for reasons not known by me, when I opened the window and closed it again and then reopened, Kendo UI scaled it to be 100x smaller. I didn't want to hack the window, so I've looked for alternative solution.
I've used jQuery 1.7.2. I've updated jQuery to version 1.8.0. and window opening, closing and reopening worked. I was very happy until I realized that now the grid filters are not working. When I click on a grid filter, nothing happens, no popup, nothing. What is the cause of this and what would be the solution?
EDIT:
This is my code (I've replaced the values of the Urls). Grid filters are working with jQuery 1.7.2. and window reopen works with new versions of jQuery. Also, if I remove the sort hack, the grid filter popup still doesn't show up.
var hshflt = {};
var addWindow;
var editWindow;
var init = false;
//Sort Hack
/*
Changes all dataSources to case insensitive sorting (client side sorting).
This snipped enable case insensitive sorting on Kendo UI grid, too.
The original case sensitive comparer is a private and can't be accessed without modifying the original source code.
tested with Kendo UI version 2012.2.710 (Q2 2012 / July 2012).
*/
var CaseInsensitiveComparer = {
getterCache: {},
getter: function (expression) {
return this.getterCache[expression] = this.getterCache[expression] || new Function("d", "return " + kendo.expr(expression));
},
selector: function (field) {
return jQuery.isFunction(field) ? field : this.getter(field);
},
asc: function (field) {
var selector = this.selector(field);
return function (a, b) {
if ((selector(a).toLowerCase) && (selector(b).toLowerCase)) {
a = selector(a).toLowerCase(); // the magical part
b = selector(b).toLowerCase();
}
return a > b ? 1 : (a < b ? -1 : 0);
};
},
desc: function (field) {
var selector = this.selector(field);
return function (a, b) {
if ((selector(a).toLowerCase) && (selector(b).toLowerCase)) {
a = selector(a).toLowerCase(); // the magical part
b = selector(b).toLowerCase();
}
return a < b ? 1 : (a > b ? -1 : 0);
};
},
create: function (descriptor) {
return this[descriptor.dir.toLowerCase()](descriptor.field);
},
combine: function (comparers) {
return function (a, b) {
var result = comparers[0](a, b),
idx,
length;
for (idx = 1, length = comparers.length; idx < length; idx++) {
result = result || comparers[idx](a, b);
}
return result;
};
}
};
kendo.data.Query.prototype.normalizeSort = function (field, dir) {
if (field) {
var descriptor = typeof field === "string" ? { field: field, dir: dir} : field,
descriptors = jQuery.isArray(descriptor) ? descriptor : (descriptor !== undefined ? [descriptor] : []);
return jQuery.grep(descriptors, function (d) { return !!d.dir; });
}
};
kendo.data.Query.prototype.sort = function (field, dir, comparer) {
var idx,
length,
descriptors = this.normalizeSort(field, dir),
comparers = [];
comparer = comparer || CaseInsensitiveComparer;
if (descriptors.length) {
for (idx = 0, length = descriptors.length; idx < length; idx++) {
comparers.push(comparer.create(descriptors[idx]));
}
return this.orderBy({ compare: comparer.combine(comparers) });
}
return this;
};
kendo.data.Query.prototype.orderBy = function (selector) {
var result = this.data.slice(0),
comparer = jQuery.isFunction(selector) || !selector ? CaseInsensitiveComparer.asc(selector) : selector.compare;
return new kendo.data.Query(result.sort(comparer));
};
kendo.data.Query.prototype.orderByDescending = function (selector) {
return new kendo.data.Query(this.data.slice(0).sort(CaseInsensitiveComparer.desc(selector)));
};
//Sort Hack
$("#refresh-btn").click(function () {
refreshGrid();
});
var grid;
function getPageIndex() {
if (!(grid)) {
return 0;
}
return grid.pager.page() - 1;
}
function getPageSize() {
if (!(grid)) {
return 10;
}
return grid.pager.pageSize();
}
function getFilters() {
if (!(grid)) {
return "";
}
return grid.dataSource.filter();
}
function getSorts() {
if (!(grid)) {
return "";
}
var arr = grid.dataSource.sort();
if ((arr) && (arr.length == 0)) {
return "";
}
var returnValue = "";
for (var index in arr) {
var type = "";
for (var col in grid.columns) {
if (grid.columns[col].field === arr[index].field) {
type = grid.columns[col].type;
}
}
returnValue += ((returnValue.length > 0) ? (";") : ("")) + arr[index].field + "," + (arr[index].dir === "asc") + "," + type;
}
return returnValue;
}
function getColumns() {
if (!(grid)) {
return "";
}
var columns = "";
for (var col in grid.columns) {
if (columns.length > 0) {
columns += ";";
}
columns += grid.columns[col].field + "," + grid.columns[col].type;
}
return columns;
}
var initGrid = true;
var grid2Data;
function getDataSource() {
$.ajax({
type: 'POST',
url: 'mydsurl' + getParams(),
data: "filter=" + JSON.stringify(getFilters()) + "&columns=" + getColumns(),
success: function (param) { grid2Data = param; },
//dataType: dataType,
async: false
});
return grid2Data.Data;
}
var shouldClickOnRefresh = false;
function refreshGrid() {
shouldClickOnRefresh = false;
$.ajax({
type: 'POST',
url: 'mydsurl' + getParams(),
data: "filter=" + JSON.stringify(getFilters()) + "&columns=" + getColumns(),
success: function (param) { grid2Data = param; },
//dataType: dataType,
async: false
});
grid.dataSource.total = function () {
return grid2Data.Total;
}
for (var col in grid.columns) {
if ((grid.columns[col].type) && (grid.columns[col].type === "Date")) {
for (var row in grid2Data.Data) {
grid2Data.Data[row][grid.columns[col].field] = new Date(parseInt((grid2Data.Data[row][grid.columns[col].field] + "").replace("/Date(", "").replace(")/", "")));
}
}
}
grid.dataSource.data(grid2Data.Data);
shouldClickOnRefresh = true;
}
function getParams() {
return getPageSize() + "|" + getPageIndex() + "|" + getSorts();
}
function bindGrid() {
var editUrl = 'myediturl';
if (!(editWindow)) {
editWindow = $("#edit-window");
}
$(".k-button.k-button-icontext.k-grid-edit").each(function (index) {
$(this).click(function () {
if (!editWindow.data("kendoWindow")) {
editWindow.kendoWindow({
title: "Edit User",
width: "60%",
height: "60%",
close: onClose,
open: onEditOpen,
content: editUrl + $("#grid").data().kendoGrid.dataSource.view()[index]["ID"]
});
}
else {
editWindow.data("kendoWindow").refresh(editUrl + $("#grid").data().kendoGrid.dataSource.view()[index]["ID"]);
editWindow.data("kendoWindow").open();
}
editWindow.data("kendoWindow").center();
return false;
})
});
$(".k-button.k-button-icontext.k-grid-delete").each(function (index) {
$(this).click(function () {
var r = confirm("Are you sure you want to delete this user?");
if (r == true) {
$.ajax({
type: 'POST',
url: 'mydelurl' + $("#grid").data().kendoGrid.dataSource.view()[index]["ID"],
success: function (param) { refreshGrid(); },
async: false
});
}
return false;
});
});
}
function onDataBound() {
if (!(shouldClickOnRefresh)) {
shouldClickOnRefresh = true;
bindGrid();
}
else {
refreshGrid();
}
}
$(function () {
$("#grid").kendoGrid({
dataBound: onDataBound,
dataSource: {
autoSync: true,
data: getDataSource(),
serverPaging: true,
schema: {
model: {
fields: {
Email: { type: "string" },
FullName: { type: "string" },
LogCreateDate: { type: "date" },
RoleName: { type: "string" },
UserName: { type: "string" }
}
},
total: function (response) {
return grid2Data.Total;
}
},
pageSize: 10
},
toolbar: ["create"],
scrollable: true,
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false,
pageSizes: true
},
columns: [
{
command: ["edit", "destroy"],
title: " "
},
{
field: "Email",
title: "Email",
type: "String"
},
{
field: "FullName",
title: "Full Name",
type: "String"
},
{
field: "LogCreateDate",
title: "Created",
type: "Date",
template: '#= kendo.toString(LogCreateDate,"MM/dd/yyyy") #'
},
{
field: "RoleName",
title: "Role",
type: "Custom"
},
{
field: "UserName",
type: "String"
}
],
editable: "popup"
});
grid = $("#grid").data("kendoGrid");
function onAddOpen() {
}
addWindow = $("#add-window");
$(".k-button.k-button-icontext.k-grid-add").click(function () {
if (!addWindow.data("kendoWindow")) {
addWindow.kendoWindow({
title: "Add User",
width: "60%",
height: "60%",
close: onClose,
open: onAddOpen,
content: 'myaddurl'
});
}
else {
addWindow.data("kendoWindow").open();
}
addWindow.data("kendoWindow").center();
addWindow.data("kendoWindow").refresh();
return false;
});
});
function onClose() {
$("#refresh-btn").click();
}
function onEditOpen() {
//editWindow.data("kendoWdinow").center();
}
I've hacked Kendo UI for the second time, this time I've solved its incompatibility with jQuery 1.8.3. using the following hack:
$(".k-grid-filter").each(function(index) {
$(this).click(function() {
$($(".k-filter-menu.k-popup.k-group.k-reset")[index]).offset({
left: $($(".k-grid-filter")[index]).offset().left - $($(".k-filter-menu.k-popup.k-group.k-reset")[index]).width(),
top: $($(".k-grid-filter")[index]).offset().top + $($(".k-grid-filter")[index]).height()})
})
});
I've put this hack into the document load event of the page an voila, it works. It surely looks ugly as hell with this hack, but after designing it will look good as new. I'm happy I found a work around, but I'm unhappy I had to hack Kendo UI twice. It is a very nice tool except the bugs.
jQuery 1.8.# is only compatible with Kendo UI - Q2 2012 SP1 (2012.2 913) or later..
If your kendo UI version is earlier, you should update it.