update/delete event for Kendo UI Grid Aurelia - grid

The update/create/delete events are not getting fired. Any idea?
View:
<ak-grid k-option.bind = "gridOptions" id="adminGrid" k-toolbar.bind="['create']" k-editable.bind="true" k-pageable.bind="true" k-sortable.bind="true">
</ak-grid>
View Model:
activate(params) {
this.name = params.type.toUpperCase();
return this.getData(this.getType(), null).then(items => {
this.getMetadata(items)
.then(metadata => {
this.gridOptions = metadata;
});
});
}
getMetadata(items) {
return new Promise(resolve => {
resolve({
columns: this.getColumns(items),
autoSync: true,
dataSource: {
transport: {
read: //alert("read"),
function (e) {
e.success(items);
},
update:
function (e) {
alert("update"),
e.success(e.data);
},
destroy: function (e) {
alert("delete");
},
parameterMap: function (options, operation) {
if (operation == "create") {
alert("create param");
}
return options;
}
},
pageSize: 10,
editable: true,
pageable: {
refresh: true,
pageSizes: true
}
}
});
});
}

Related

Ajax and error cannot read properties of undefined

So I am trying to get some data from a table using ajax but this error keeps popping up and I know its related to parameters but I have none of the parameters it says are wrong anyone got any ideas?
I am working in asp.net 6 and am trying to get the data to a controller.
I am currently working in C# and ajax
(function () {
"use strict"
window.onload = function () {
//Reference the DropDownList.
var ddlYears = document.getElementById("ddlYears");
//Determine the Current Year.
var currentYear = (new Date()).getFullYear() + 10;
var less = (new Date()).getFullYear() - 10;
//Loop and add the Year values to DropDownList.
for (var i = less; i <= currentYear; i++) {
var option = document.createElement("OPTION");
option.innerHTML = i;
option.value = i;
ddlYears.appendChild(option);
}
};
var ScopeTable;
$(document).ready(function () {
ScopeTable = $("#tblScopeView").DataTable({
dom: "Bfrtip",
paging: true,
pagingType: "full_numbers",
buttons: [
"csvHtml5"
],
columns: [
{ data: 'WBS' },
{ data: 'Title' },
{ data: 'Rev' },
{ data: 'ScopeStatus' },
{ data: 'BCP' },
{ data: 'BCPApprovalDate' },
{ data: 'Manager' },
{ data: 'ProjectControlManager' },
{ data: 'ProjectControlEngineer' },
{
mRender: function (data, type, row) {
return "<i class='fa fa-edit btnAddEditScope'></i><span> Edit</span >"
},
class: "btnAddEditScope table-button",
orderable: false
},
{
mRender: function (data, type, row) {
return "<i class='fa fa-trash btnDeleteRow'></i><span> Delete</span >"
},
orderable: false,
class: "table-button"
}
],
createdRow: function (row, data, index) {
$(row).attr("data-id", data.WBSNumber);
$(row).attr("data-month", data.FiscalMonth);
$(row).attr("data-year", data.FiscalYear);
}
});
$(document).on("click", ".btnAddEditScope", btnAddEditScope_click);
$("#spnrSave").hide();
});
function btnAddEditScope_click() {
console.log("button clicked")
$.ajax({
url: "Scope/AddEditScope",
type: "GET",
success: function () {
$("#vw_AddEditScope").modal("show");
}
});
}
}());
Error that is being posted
Figured it out just had do adjust my ajax and it worked fine. The tutorial I found is here https://datatables.net/examples/api/multi_filter.html
var ScopeTable;
$(document).ready(function (e) {
ScopeTable = $("#tblScopeView").DataTable({
dom: "Bfrtip",
paging: true,
pagingType: "full_numbers",
buttons: [
"csvHtml5"
],
columns: [
{ data: 'WBS' },
{ data: 'Title' },
{ data: 'Rev' },
{ data: 'ScopeStatus' },
{ data: 'BCP' },
{ data: 'BCPApprovalDate' },
{ data: 'Manager' },
{ data: 'ProjectControlManager' },
{ data: 'ProjectControlEngineer' },
{
mRender: function (data, type, row) {
return "<i class='fa fa-edit btnAddEditScope'></i><span> Edit</span >"
},
class: "btnAddEditScope table-button",
orderable: false
}, {
mRender: function (data, type, row) {
return "<i class='fa fa-trash btnDeleteRow'></i><span> Delete</span >"
},
orderable: false,
class: "table-button"
},
],
createdRow: function (row, data, index) {
$(row).attr("data-id", data.WBSNumber);
$(row).attr("data-month", data.FiscalMonth);
$(row).attr("data-year", data.FiscalYear);
},
error: function (e) {
console.log(e);
}
});
$('#tblScopeView tfoot th').each(function () {
var title = $("#tblScopeView").eq($(this).index()).text();
$(this).html('<input type="text" class="form-control" placeholder="Search ' + title + '" />');
ScopeTable.columns().every(function () {
var dataTableColumn = this;
$(this.footer()).find('input').on('keyup change', function () {
dataTableColumn.search(this.value).draw();
});
});
});
$("#spnrSave").hide();
$(document).on("click", ".btnAddEditScope", btnAddEditScope_click);
});

FullCalendar initializing before events load

I have a FullCalendar that takes in an array(selectedEvents) from a function that uses the Location ID that is pulled from the url. The array is built onInit as is the calendar but the calendar has a timeout on it in order to allow the events to populate. When the calendar is initially navigated to from another part of the website, the events for the Default Location are not displayed but they are populated into the selectedEvents array. When I click on another location's calendar, the events are populated and then displayed correctly. The calendar works correctly thereforth. I believe the calendar is taking precedence over the population of events during the first initialization of the calendar even though it is wrapped in a timeout. I've seen this question once before on SO but it was not answered.
I've already tried extending the timeout of the calendar
getLocationEvents(location: PFLocation) {
// if (this.allEvents) {
this.selectedEvents = [];
if (location.events) {
console.log(location.events);
this.eventIdArray = location.events;
for (let event of this.eventIdArray) {
this.eventService.get(event).subscribe(data => {
console.log(data);
this.selectedEvents.push(data);
});
}
} else {
return;
}
console.log(this.selectedEvents);
return this.selectedEvents;
}
getBatchEvents(location: PFLocation) {
var that = this;
if (this.allEvents) {
if (location.batches) {
let batches = location.batches;
for (let batch of batches) {
this.batchService.get(batch).subscribe(data => {
for (let event of data.events) {
this.eventService
.get(event)
.subscribe(eventData => {
console.log(eventData);
this.selectedEvents.push(eventData);
});
}
});
}
console.log(this.selectedEvents);
console.log('out of Batch Events');
return this.selectedEvents;
}
}
if (!this.allEvents) {
this.selectedEvents = [];
if (location.batches) {
let batches = location.batches;
for (let batch of batches) {
this.batchService.get(batch).subscribe(data => {
for (let event of data.events) {
this.eventService
.get(event)
.subscribe(eventData => {
console.log(eventData);
this.selectedEvents.push(eventData);
});
}
});
}
console.log(this.batchEvents);
console.log('out of Batch Events');
return this.selectedEvents;
}
}
}
getAllEvents(location: PFLocation) {
this.allEvents = true;
var that = this;
that.getLocationEvents(location);
that.getBatchEvents(location);
}
ngOnInit() {
let that = this;
this.sub = this.route.params.subscribe(params => {
this.locationId = params['locationid'];
this.userService
.getLocation(this.locationId)
.subscribe(location => {
console.log('Out of on Init');
this.selectedLocation = JSON.parse(
JSON.stringify(location)
);
that.getAllEvents(this.selectedLocation);
console.log(this.selectedLocation);
});`enter code here`
console.log(this.selectedLocation);
if (this.locationId) {
const today = new Date();
const y = today.getFullYear();
const m = today.getMonth();
const d = today.getDate();
$('#fullCalendar').fullCalendar('removeEvents');
$('#fullCalendar').fullCalendar(
'addEventSource',
that.selectedEvents
);
setTimeout(function() {
$('#fullCalendar').fullCalendar({
viewRender: function(view: any, element: any){
// We make sure that we activate the
perfect scrollbar when the view isn't on Month
if (view.name != 'month') {
var elem = $(element).find('.fc-
scroller')[0];
let ps = new PerfectScrollbar(elem);
}
},
header: {
left: 'title',
center: 'month, agendaWeek, agendaDay',
right: 'prev, next, today'
},
defaultDate: today,
selectable: true,
selectHelper: true,
views: {
month: {
// name of view
titleFormat: 'MMMM YYYY'
// other view-specific options here
},
week: {
titleFormat: ' MMMM D YYYY'
},
day: {
titleFormat: 'D MMM, YYYY'
}
},
eventLimit: true, // allow "more" link when
too many events
select: function(start: any, end: any) {
that.openEventForm();
},
eventClick: function(event, jsEvent) {
that.completeEventForm(event);
}
});
}, 500);
}
});
}
I expect the calendar to be populated the first time I navigate to the page.
Aside from refactoring the backend and eliminating the spaghetti code it wasn't a difficult issue once someone pointed out how the calendar inits. First the calendar has to grab onto the DOM element then it grabs the event source. If it doesn't grab the #calendar then it won't grab the event source until the next time it's initialized and at that point it is using the old event source data(if set up as my code was). "viewRender" needs to happen first, then "removeEvents" then "addEventSource".
getLocationEvents(location: PFLocation) {
if (location.events) {
return this.eventService
.getFaciltyTasks(location._id)
.subscribe(data => {
console.log(data);
this.facilityEvents = data;
});
}
}
getAllBatchEvents(location: PFLocation) {
return this.eventService
.getAllCultivationTasks(location._id)
.subscribe(data => {
console.log(data);
this.cultivationEvents = data;
});
}
getBatchEvents(batchId: string) {
return this.eventService.getBatchTasks(batchId).subscribe(data => {
console.log(data);
this.batchEvents = data;
});
}
editEventForm() {
this.state = 'editEvent';
}
getAllEvents(location: PFLocation) {
var that = this;
return new Promise(resolve => {
return this.eventService
.getAllLocationTasks(location._id)
.subscribe(data => {
console.log(data);
that.selectedEvents = data;
that.calInit();
resolve(that.selectedEvents);
});
});
}
calInit() {
var that = this;
const $calendar = $('#fullCalendar');
console.log(that.locationId);
if (this.selectedEvents) {
const today = new Date();
const y = today.getFullYear();
const m = today.getMonth();
const d = today.getDate();
$calendar.fullCalendar({
viewRender: function(view: any, element: any) {
// We make sure that we activate the perfect scrollbar when the view isn't on Month
if (view.name != 'month') {
var elem = $(element).find('.fc-scroller')[0];
let ps = new PerfectScrollbar(elem);
}
},
customButtons: {
filter: {
text: 'filter',
click: function() {
that.open();
}
}
},
// events: that.selectedEvents,
header: {
left: 'title',
center: 'filter, month, agendaWeek, agendaDay',
right: 'prev, next, today'
},
defaultDate: today,
selectable: true,
selectHelper: true,
views: {
month: {
// name of view
titleFormat: 'MMMM YYYY'
// other view-specific options here
},
week: {
titleFormat: ' MMMM D YYYY'
},
day: {
titleFormat: 'D MMM, YYYY'
}
},
eventLimit: true, // allow "more" link when too many events
select: function(start: any, end: any) {
that.openEventForm();
},
eventClick: function(event, jsEvent) {
that.eventLocation = new PFLocation({});
that.eventBatch = new Batch();
that.eventRoom = new Room();
that.viewEvent(event);
}
});
$calendar.fullCalendar('removeEvents');
$calendar.fullCalendar('addEventSource', that.selectedEvents);
}
}
ngOnInit() {
// const $calendar = $('#fullCalendar');
let that = this;
// that.filter = false;
this.sub = this.route.params.subscribe(params => {
that.locationId = params['locationid'];
if (that.locationId) {
that.AuthService.getCurrentUser().then(user => {
that.currentUser = user;
var locations = that.currentUser.locations.admin.concat(
that.currentUser.locations.user
);
var location = find(locations, function(location) {
return location._id == that.locationId;
});
console.log(location);
console.log(that.currentUser);
});
}
this.userService
.getLocation(this.locationId)
.subscribe(location => {
console.log('Out of on Init');
this.selectedLocation = JSON.parse(
JSON.stringify(location)
);
that.getAllEvents(this.selectedLocation);
console.log(this.selectedLocation);
});
console.log(this.selectedLocation);
});
}

FullCalendar input is undefined in eventDataTransform

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;

Error when updating an object in auto-form with meteor

I have checked the docs but I cannot get my head around this. I have an object that I want to update using Auto-Form and Collections2 with meteor.
//Schema
Records = new Mongo.Collection('records');
var Schemas = {};
Schemas.Record = new SimpleSchema({
title: {
type: String,
label: "Title",
max: 200
},
caption: {
type: String,
label: "Caption",
max: 200
},
text: {
type: String,
label: "Detailed text",
optional: true,
max: 1000
},
loc: {
type: Object,
optional: true,
blackbox: true
},
createdAt: {
type: Date,
autoform: {
type: "hidden"
},
autoValue: function() {
if (this.isInsert) {
return new Date;
}
else if (this.isUpsert) {
return {
$setOnInsert: new Date
};
}
else {
this.unset();
}
}
},
updatedBy: {
type: String,
autoValue: function() {
return Meteor.userId();
}
}
});
Records.attachSchema(Schemas.Record);
I have a hook so that I assign the object before update
AutoForm.hooks({
insertCommentForm: {
before: {
insert: function(doc) {
doc.commentOn = Template.parentData()._id;
return doc;
}
}
},
updateRecordForm: {
before: {
update: function(doc) {
console.log("storing location data");
doc.loc = Session.get('geoData');
console.log(doc.loc);
return doc;
}
}
}
});
I get this error.
Uncaught Error: When the modifier option is true, all validation
object keys must be operators. Did you forget $set?
I don't know how to "$set" with autoform.
when you are trying to update a document in Mongo, when you want to update only certain fields, you will use the $set modifier.
Records.update({ _id: 1 }, { $set: { loc: { lat: 12, lng: 75 } } })
The above would update only the loc value.
Records.update({ _id: 1 }, { loc: { lat: 12, lng: 75 } })
The above would remove all other keys and the record will only have the _id and the loc.
Your hook will have to set the loc key in doc.$set.
Please update your hook with the following code and it should work:
updateRecordForm: {
before: {
update: function(doc) {
console.log("storing location data", doc);
doc.$set.loc = Session.get('geoData');
return doc;
}
}
}

JSON Data not displaying in ng-grid in angular

I've got a controller that makes an HTTP Call to the database. It returns the data, verified by the $log command but does not display it in the grid. Here's the code..
Thanks in advance...
eventsApp.controller('TerrController',
function TerrController($scope, territoryData) {
$scope.territory = [];
//$scope.gridOptions = {
// data: 'territory', columnDefs: [
// { field: 'TerritoryID', displayName: 'ID'},
// { field: 'TerritoryDescription', displayName: 'Description' },
// { field: 'RegionID', displayName: 'RegionID' }]
//};
territoryData.getTerritories().then(function (response) {
var tmpData = angular.fromJson(response);
$scope.territory = tmpData;
});
$scope.gridOptions = {
data: 'territory', columnDefs: [
{ field: 'RegionID', displayName: 'RegionID', visible: true },
{ field: 'TerritoryDescription', displayName: 'Description', visible: true },
{ field: 'TerritoryID', displayName: 'ID', visible: true }]
};
});
eventsApp.factory('territoryData', function ($http, $q, $log) {
return {
getTerritories: function () {
var deferred = $q.defer();
$http({ method: 'GET', url: '/Home/GetTerritories' }).
success(function (result, status, headers, config) {
angular.forEach(result, function (c) {
$log.log(c.TerritoryDescription);
});
deferred.resolve(result);
}).
error(function (result, status, headers, config) {
deferred.reject(status)
});
return deferred.promise;
}
}
});

Resources