Fullcalendar - Can we add custom data to our event Json Data? - javascript

I want to send a type in my Event Json Response.
Here is my code:
$('#calendar').fullCalendar({
eventSources: [
{"id":"46_l","title":"CustomEvent-Chargement","start":"2013-12-02","end":"2013-12-03","className":"customEventsClass","type":1},
{"id":"46_d","title":"Custom Event-Livraison","start":"2013-12-11","end":"2013-12-12","className":"customEventsClass","type":2}
]
});
You see I send a type in JSON Response array, is this possible? What parameter can we use for sending our custom data?

As per the documentation:
Non-standard Fields
In addition to the fields above, you may also include your own non-standard fields in each Event Object. FullCalendar will not modify or delete these fields. For example, developers often include a description field for use in callbacks such as eventRender.
Example:
$('#calendar').fullCalendar({
events: [
{
title: 'My Event',
start: '2010-01-01',
type: 1 // Custom field
}
],
eventRender: function(event, element) {
console.log(event.type); // Writes "1"
}
});

Try It with events: instead of eventSources:
$('#calendar').fullCalendar({
events: [
{"id":"46_l","title":"CustomEvent-Chargement","start":"2013-12-02","end":"2013-12-03","className":"customEventsClass","type":1},
{"id":"46_d","title":"Custom Event-Livraison","start":"2013-12-11","end":"2013-12-12","className":"customEventsClass","type":2}
]
});

In the new version you should do this:
eventRender: function (info) {
info.el.firstChild.innerHTML = info.event.extendedProps.type + " " + info.event.extendedProps.customEventsClass;
}

In version 4 custom data is in extendedProps.
In short e.event.extendedProps

You can also pass url endpoint to events as long as the url returns json response
cId.fullCalendar({
header: {
right: '',
center: 'prev, title, next',
left: ''
},
theme: true, //Do not remove this as it ruin the design
selectable: true,
selectHelper: true,
editable: true,
//it will load data from this url
events: "{{ url('api/events') }}",
// events: getData(),
//Add Events
});
and in your controller or function
$events = $request->user()->events()->select('title','color','date')->get();
// dd($even,$events)
$eventsResponse = [];
// created_at->format('Y-m-d')
foreach ($events as $event)
{
$eventsResponse[] = [
'title'=>$event->title,
'color'=>$event->color,
'start'=> Carbon::parse($event->date)->toDateTimeString(),
];
}
return $eventsResponse;

Related

Fullcalendar: How to remove event

Thanks to another post here on StackOverflow, I added some code to my select: method that prevents users from adding an event on a date prior to NOW.
The downside is that when they click on the empty time slot, and the system then complains (an alert message), the attempted event remains. How do I get rid of it? Thanks!
Update: Here's my code:
select: function(start, end, jsEvent) {
var check = start._d.toJSON().slice(0,10),
today = new Date().toJSON().slice(0,10),
m = moment(),
url = "[redacted]",
result = {};
title = "Class",
eventData = {
title: title,
start: start,
end: start.clone().add(2, 'hour'),
durationEditable: false,
instructorid: 123,
locationid: 234
};
if(check < today) {
alert("Cannot create an event before today.");
$("#calendar").fullCalendar('removeEvents', function(eventObject) {
return true;
});
} else {
$.ajax({ type: "post", url: url, data: JSON.stringify(eventData), dataType: 'JSON', contentType: "application/json", success: function(result) {
if ( result.SUCCESS == true ) {
$('#calendar').fullCalendar('renderEvent', eventData, true);
$('#calendar').fullCalendar('unselect');
} else {
alert(result.MESSAGE);
}
}});
}
}
If you're using FullCalendar V2, you need to use the removeEvents method.
You can use it to delete events with a certain ID by calling it in this way:
$("#calendar").fullCalendar('removeEvents', 123); //replace 123 with reference to a real ID
If you want to use your own function that decides whether or not an event get's removed, you can call it this way:
$("#calendar").fullCalendar('removeEvents', function(eventObject) {
//return true if the event 'eventObject' needs to be removed, return false if it doesn't
});
FullCalendar has a removeEvent method that uses an id when you create the event.
Example Full Calendar v1:
var calendar = $('#calendar').fullCalendar({ ... stuff ... });
calendar.fullCalendar( 'addEventSource', {id:123, stuff:'stuff'});
// ... other calendar things here...
calendar.fullCalendar( 'removeEvent', 123);
Reference API v1
Example FullCalendar v2:
var calendar = $('#calendar').fullCalendar({ ... stuff ... });
calendar.fullCalendar( 'addEventSource', {id:123, stuff:'stuff'});
// ... other calendar things here...
calendar.fullCalendar( 'removeEvents', [123]);
Reference API v2
Version 4.3
calendar = new Calendar(calendarEl, {
plugins : [ 'interaction', 'dayGrid', 'list' ],
header : {
left : 'prev,next today',
center : 'title',
right : 'dayGridMonth,timeGridWeek,timeGridDay,list'
},
editable : true,
droppable : true,
eventReceive : function(info) {
alert(info.event.title);
},
eventDrop : function(info) {
alert(info.event.title + " was dropped on "
+ info.event.start.toISOString());
if (!confirm("Are you sure about this change?")) {
info.revert();
}
},
eventClick : function(info) {
//delete event from calender
info.event.remove();
}
});
calendar.render();
});
Full calendar version 4
How to remove event from calendar:
<div id="calendar"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new Calendar(calendarEl, {
events: [
{
id: '505',
title: 'My Event',
start: '2010-01-01',
url: 'http://google.com/'
}
// other events here
],
eventClick: function(info) {
info.jsEvent.preventDefault(); // don't let the browser navigate
if (info.event.id) {
var event = calendar.getEventById(info.event.id);
event.remove();
}
}
});
});
</script>
This worked for me. I hope, this will also help you. Thanks for asking this question.

Display date from database using jquery fullcalendar

I'm using the jquery fullcalendar plugin. I can display dynamic dates on a button click. The issue I have now is when loading the dates from the db all the dates populate just one day.
Here is the code with the call to the web service:
$('#calendar').fullCalendar({
header: {
left: 'prev, next today',
center: 'title',
right: 'month, agendaWeek, agendaDay'
},
defaultView: 'month',
editable: true,
allDaySlot: false,
selectable: true,
slotMinutes: 15,
events: 'DAL/WebService1.asmx/GetEvents',
allDay:false
});
Here is the date from that web method
$('#calendar').fullcalendar('renderEvent',event_object,'stick')
This will attach your event to its date on the calendar. The event_object only needs a title and a start date to be valid, but I'd suggest adding an id to make editing/deleting easier.
Render event documentation
Figured out how to get the calendar to render dates separately with this code here. Hopefully helps somebody in the future
var events = [];
$('#calendar').fullCalendar({
events: function (start, end, timezone,callback) {
$.ajax({
url: 'DAL/WebService1.asmx/GetEvents',
dataType: 'json',
success: function (data) {
console.log(data);
var events = [];
$(data).each(function (index, d) {
events.push({
title: d.title,
start: d.startDate
});
});
callback(events);
}
});
}
});

How can i read events from my database table and show them in their respective dates in java script and jquery

i use Full calendar plugin to do this and i have done something but still did not get up to mark.
hear is my scripting code
$('#calendar').fullCalendar({
//theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
buttonText: {//This is to add icons to the visible buttons
prev: "<span class='fa fa-caret-left'></span>",
next: "<span class='fa fa-caret-right'></span>",
today: 'today',
month: 'month',
week: 'week',
day: 'day'
},
editable: true,
droppable: true, // this allows things to be dropped onto the calendar
drop: function(date) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.backgroundColor = $(this).css("background-color");
copiedEventObject.borderColor = $(this).css("border-color");
console.log(copiedEventObject);
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
/*alert(date + ' was moved ' + allDay + ' days\n' +
'(should probably update your database)');*/
},
//events:"web_master/mycal/ajax_fetch_calendar_data",
events: function(start, end, timezone, callback) {
$.ajax({
url: 'web_master/mycal/ajax_fetch_calendar_data',
dataType: 'json',
type: "POST",
success: function(doc) {
//console.log(doc);
var events = [];
$(doc).find('event').each(function(){
console.log(doc);
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
}
});
},
});
in this i successfully found my doc in events section.
here is the code to fetch events from DB
public function ajax_fetch_calendar_data()
{
try
{
$info = $this->mod_rect->fetch_calendar();
#pr($info);
for($i = 0 ; $i < count($info) ; $i++)
{
$rows[]= array("id"=>$info[$i]['i_id'],
"title"=> $info[$i]['s_title'],
"start"=> $info[$i]['dt_start_date'],
"end"=>$info[$i]['dt_end_date'],
"allDay"=> $info[$i]['s_allDay']);
}
if($rows)
{
echo json_encode($rows);
}
}
catch(Exception $err_obj)
{
show_error($err_obj->getMessage());
}
}
but there is an find(event) function which is didn't found.
Basically what i need to do that
i have some events, those are fetch from DB and i have to drag them on the specific date on the date that comes(upto this done), but i want to store that in Db and fetch them from DB.
I am new to java script and jquery and i didn't know about JSON also.
any help regarding this will helpfull to me.
Thanks.
Well
After few days I have done it myself.
And I think it would be help full to someone So i update my Question
In the Events Section of Fullcalendar for reading multiple events and showing them in your Fullcalendar
events: function(start, end, callback) {
$.ajax({
url: 'web_master/mycal/ajax_fetch_calendar_data',
dataType: 'json',
type: "POST",
success: function(doc) {
var eventObject = [];
for(i=0;i<doc.length;i++)
{
eventObject.push({
id : doc[i].id,
start : doc[i].start,
end : doc[i].end,
title : doc[i].title
//allDay : doc[i].allDay,
//backgroundColor : doc[i].backgroundColor,
//borderColor : doc[i].borderColor
});
}
callback(eventObject);
}
});
},
And i fetch it from my DB in this way
public function ajax_fetch_calendar_data()
{
try
{
$info = $this->mod_rect->fetch_calendar();
echo json_encode($info);
}
catch(Exception $err_obj)
{
show_error($err_obj->getMessage());
}
}

How can I populate a calendar with javascript?

I'm trying to develop an application where I need to use this calendar : http://fullcalendar.io/
The problem is that I can populate it manually, but I can't populate it from my Database.
This is the function that populates the calendar:
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
eventLimit: true,
events:[
{
title: "aaaa",
start: "2014-12-12"
},
{
title: "bbb",
start: "2014-12-13"
}
]
});
});
and this is the function that allows me to get my data from the Database:
function getEvents(db){
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM NOTES', [], function (tx, results) {
// var allEvents = [];
var allEvents=[];
for (var i = 0; i < results.rows.length; i++){
//var event = {};
allEvents.push({
title: results.rows.item(i).note,
start: results.rows.item(i).whenn
});
}
$.each(allEvents, function(idx, obj){
alert(obj.title);
});
}, null);
});
};
When i call the function getEvents(db) in events, it shows me the alerts but doesn't populate the calendar.
PS: I can't use php files.
You can use renderEvent
.fullCalendar( 'renderEvent', event [, stick ] )
which, as the name suggests, renders a new event on the calendar.
According to the docs, event must be an Event Object with a title and start at the very least. Normally, the event will disappear once the calendar refetches its event sources (example: when prev/next is clicked). However, specifying stick as true will cause the event to be permanently fixed to the calendar.
For you, I guess this would translate to something like:
$.each(allEvents, function(idx, obj){
$('#calendar').fullCalendar( 'renderEvent', obj);
});
I've not used fullCalendar, but if this doesn't work, make a fiddle of what you've got and I'll make you a working example.

Backbone Collection is populated with models but cannot pull JSON out of it... simple answer I'm sure

Thank you for all the help this community has given me, I am extremely grateful. If anyone knows what im doing incorrectly I would love to figure this out :)
The Problem:
I just started using backbone. lol But really, I am trying building and app that uses full calendar and backbone to populate the calendar. Everything is going smooth so far and I am able to add new sessions with the correct start and end dates to the calendar.
But on the initial load none of these session models populate on the calender. Here is a screenshot of what I am getting in console.log:
As you can see when I call jus the collection you can see it is full of models. But when I try to convert to JSON it comes up empty. I have found numerous answers on Stack Overflow about this and none of them seems to make this work. I am officially roadblocked. lol
Here is some code im working with to display collection
var Event = Backbone.Model.extend({
methodToURL: {
'create': addDayURL,
'update': addDayURL,
//'delete': '/user/remove'
},
sync: function(method, model, options) {
options = options || {};
options.url = model.methodToURL[method.toLowerCase()];
Backbone.sync(method, model, options);
}
});
var Events = Backbone.Collection.extend({
model: Event,
url: allDaysURL
});
The view is huge so I wil only include the relavent parts:
var EventsView = Backbone.View.extend({
events: {
'click #add_track' : "addTrack"
},
initialize: function(){
_.bindAll(this);
this.collection.bind('reset', this.addAll);
this.collection.bind('add', this.addOne);
this.collection.bind('change', this.change);
this.collection.bind('destroy', this.destroy);
this.eventView = new EventView();
console.log('this.collection: ', this.collection);
console.log('this.collection.toJSON(): ', this.collection.toJSON());
console.log('JSON.stringify(this.collection.toJSON()): ', JSON.stringify(this.collection.toJSON()));
//console.log(this.collection.toJSON())
// your model2 option: this.options.collection2.toJSON();
//console.log(this.options.collection2.toJSON());
},
render: function() {
this.$el.fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay',
},
//defaultView: 'resourceDay',
resources: //this.options.collection2.toJSON()
[
{
/*
* trackID
* name
* backgroundColor
* foregroundColor*/
id: 1,
name: 'Track 1',
color: 'red',
textColor: 'black'
},
{
id: 2,
name: 'Track 2',
color: 'blue'
},
{
id: 3,
name: 'Track 3',
color: 'pink'
},
{
id: 4,
name: 'Track 4',
color: 'green'
},
{
id: 5,
name: 'Track 5',
color: 'yellow',
textColor: 'black'
}
],
droppable: true,
selectable: true,
selectHelper: true,
editable: true,
ignoreTimezone: false,
select: this.select,
eventClick: this.eventClick,
eventDrop: this.eventDropOrResize,
eventResize: this.eventDropOrResize,
drop: function(date, allDay, ev, ui, res) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.allDay = allDay;
// dropped event of resource a to a cell belonging to resource b?
copiedEventObject.resourceId = res.id;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
this.addOne;
}
});
this.$el.prepend('<button id="add_track" class="btn large-btn green-btn pull-right">Add Track</button>');
},
addAll: function() {
this.$el.fullCalendar('addEventSource', this.collection.toJSON());
},
addOne: function(event) {
this.$el.fullCalendar('renderEvent', event.toJSON());
}
EDIT:
To initialize collection and populate this code resides at the bottom fo the file:
var events = new Events();
var tracks = new Tracks();
new EventsView({el: $("#calendar"), collection: events, collection2: tracks}).render();
new AddSessionView({ collection: events}).render();
events.fetch();
I'm also new to Backbone but maybe this helps. Have you tried to convert the models property of your Collection object to JSON, like:
JSON.stringify(collection.models)
This approach worked for me.
JSFiddle: http://jsfiddle.net/YcFmB/
try this :
var events = new Events();
var tracks = new Tracks();
events.fetch();
new EventsView({el: $("#calendar"), collection: events, collection2: tracks}).render();
new AddSessionView({ collection: events}).render();
I read that fetch() was an asynchronous operation, therefore when you fetch a collection, the ajax call will be sent and then your code will continue being run just like nothing happened.
I ended up creating my creating my first view inside the fetch() success handler:
events.fetch({success: function (models) {
tracks.fetch({success: function (models) {
new EventsView({el: $("#calendar"), collection: events, collection2: tracks}).render();
}});
}});
Could be an async issue in that events.fetch(); is returning after your views have been called. I use deferreds to deal with this.
var events = new Events();
var tracks = new Tracks();
$.when( events.fetch() )
.done( function(data) {
console.dir(data)
new EventsView({el: $("#calendar"), collection: events, collection2: tracks}).render();
new AddSessionView({ collection: events}).render();
});
Although, your bind on reset, should take care of that...
EDIT:
I would be curious to know what your console readout above was?

Categories

Resources