fullcalendar 4.0 use loop to set events dynamically - javascript

I'm trying to use the full calendar to set an event dynamically.By using function loadData().But I couldn't work successfully.
Could anybody please let me know how to solve this problem?
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var temp_array = loadData();
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
editable: true,
eventLimit: true, // allow "more" link when too many events
header:{
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth'
},
plugins: [ 'interaction','dayGrid' ],
for (let i = 0 ; i <temp_array.length ; i++){
calendar.addEvent({
title: temp_array[i][0],
start:temp_array[i][1],
end :temp_array[i][2]
})
}
});
calendar.render();
});
function loadData(){
let temp_array=[];
temp_array[0]=["test1","2019-07-16","2019-07-21"];
temp_array[1] = ["test2","2019-07-15","2019-07-20"];
temp_array[2] =["test1","2019-07-16",""];
return temp_array;
}
I tried this it throws an
exception: Uncaught SyntaxError: Unexpected identifier

plugins: [ 'interaction','dayGrid' ],
for (let i = 0 ; i <temp_array.length ; i++){
calendar.addEvent({
title: temp_array[i][0],
start:temp_array[i][1],
end :temp_array[i][2]
})
}
You cannot put a for loop inside an object like that. You can pass events as an array to calendar's config: https://fullcalendar.io/docs/events-array
EDIT:
If you want dynamic events, you can also pass a function: https://fullcalendar.io/docs/event-source-object#options

Related

Using php array in fullCalendar

I used the latest javascript fullCalendar (https://fullcalendar.io/) on a wordpress webpage to be able to display appointments of a wordress my users. So far the Callendar shows up on the page. Now I want to get the appointments from the db and display them in the Calendar.
If I create an array in php, with the appointments to display as a string, the appoinment shows up in the calendar.
Example:
$events = $wpdb->get_results("SELECT * FROM wp_projekt_calendar WHERE calendar_author=$uid");
foreach($events AS $event){
$array['title']= 'rtrt';
$array['start']= '2020-08-10 10:00:00';
$array['end'] = '2020-08-10 11:00:00';
}
echo json_encode($array);
But if I use the query results to show the appointment it doesent work (query works well!):
foreach($events AS $event){
$array['title']= $event_array->calendar_title;
$array['start']= $event_array->calendar_startdate .' '.$event_array->calendar_starttime;
$array['end'] = $event_array->calendar_enddate .' '.$event_array->calendar_endtime;;
}
echo json_encode($array);
This is how my calendar looks like:
<script>
document.addEventListener('DOMContentLoaded', function() {
var initialLocaleCode = 'de';
var localeSelectorEl = document.getElementById('locale-selector');
var calendarEl = document.getElementById('calendar');
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = new FullCalendar.Calendar(calendarEl, {
height: '100%',
expandRows: true,
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
initialView: 'dayGridMonth',
locale: initialLocaleCode,
navLinks: true, // can click day/week names to navigate views
editable: true,
selectable: true,
nowIndicator: true,
dayMaxEvents: true, // allow "more" link when too many events
events: {
url: "https://mydomainxy.com/wp-content/themes/gambit-child/events.php?uid='<?php // $anwender_id ?>'",
//url: "https://mydomainxy.com/wp-content/themes/gambit-child/php/get-events.php'",
type: 'POST',
error: function() {
alert('There was an error while fetching events.');
}
}
});
calendar.render();
});
</script>
What am I doing wrong or how can I get this to work?

Programmatically change date of fullcalendar 4

I am using fullcalendar v4. I have a mini calendar that once an event is clicked, I want another larger calendar (calendar_full) to go to that date.
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var calendar1 = document.getElementById('calendar_mini');
var calendar_mini = new FullCalendar.Calendar(calendar1, {
plugins: ['interaction', 'dayGrid'],
eventClick: function(info) {
//when clicking on events, go to date on main calendar
calendar.gotoDate(info.event.start)
}
...
});
document.addEventListener('DOMContentLoaded', function() {
var calendar_full = document.getElementById('calendar_full');
var calendar = new FullCalendar.Calendar(calendar_full, {
plugins: ['interaction', 'resourceDayGrid', 'resourceTimeGrid', 'timeGrid'],
header: {
right: 'prevYear,prev,next,nextYear,today',
left: 'title',
center: 'resourceTimeGridDay,resourceTimeGridWeek,resourceDayGridMonth'
},
selectMirror: true,
...
)};
In the calendar_mini code, the eventClick function of calendar.gotoDate(info.event.start) does NOT change the main calendar. I get error:
Uncaught ReferenceError: calendar is not defined
The problem is that the variable called "calendar" is not in scope when you use it in the callback, which is why it's undefined. Its scope is limited to the "DOMContentLoaded" callback in which you declared it.
Now, you don't need need two separate "DOMContentLoaded" callbacks here. One is generally sufficient for all the code that needs to be run when the page has loaded.
If you move everything inside a single callback, you won't have a problem:
document.addEventListener('DOMContentLoaded', function() {
var calendar1 = document.getElementById('calendar_mini');
var calendar_mini = new FullCalendar.Calendar(calendar1, {
plugins: ['interaction', 'dayGrid'],
eventClick: function(info) {
//when clicking on events, go to date on main calendar
calendar.gotoDate(info.event.start)
}
var calendar_full = document.getElementById('calendar_full');
var calendar = new FullCalendar.Calendar(calendar_full, {
plugins: ['interaction', 'resourceDayGrid', 'resourceTimeGrid', 'timeGrid'],
header: {
right: 'prevYear,prev,next,nextYear,today',
left: 'title',
center: 'resourceTimeGridDay,resourceTimeGridWeek,resourceDayGridMonth'
},
selectMirror: true,
...
)};

FullCalendar trying to fetch events from URL instead of array

Using FullCalendar v3.9.0 with jQuery v3.3.1. I have a SailsJS application that's getting the calendar data from MySQL.
this.me.calendar from MySQL currently looks like this.
[{"start":"2018-07-04T13:30:00","end":"2018-07-04T18:00:00","works":["2"]}]
And my FullCalendar code looks like this.
let that = this;
that.me.calendar = this.me.calendar;
$('#calendar').fullCalendar({
header: {
left: 'today prev,next',
center: 'title',
right: 'agendaWeek,agendaDay'
},
views: {
week: {
titleFormat: 'DD.MM.YYYY'
}
},
defaultView: 'agendaWeek',
locale: 'fi',
weekends: false,
scrollTime: '07:00',
businessHours: {
start: '7:00',
end: '21:00',
},
events: function(start, end, timezone, callback) {
let events = that.me.calendar ? that.me.calendar : [];
console.log(events);
callback(events);
},
editable: true,
selectable: true,
selectHelper: true,
select: (start, end) => {
let duration = (end - start) / 1000;
if (duration == 1800) {
// Set default duration to 1 hour
end = start.add(30, 'mins');
return $('#calendar').fullCalendar('select', start, end);
}
let eventData = {
start: start,
end: end,
works: []
}
$('#calendar').fullCalendar('renderEvent', eventData);
$('#calendar').fullCalendar('unselect');
},
eventClick: (event, element) => {
$('#event-works').text(event.works.join(','));
$('#start-date').text(moment(event.start).format('d.MM.YYYY HH:mm'));
$('#end-date').text(moment(event.end).format('d.MM.YYYY HH:mm'));
$('#workModal').modal('show');
$('#add-work-to-event').click(() => {
let work = $('#work').val();
if(_.includes(event.works, work)) return;
event.works.push(work);
$('#event-works').text(event.works.join(','));
});
}
});
While the code above doesn't send the GET, it doesn't display the events in the calendar. However, if I change the events to events: this.me.calendar, the SailsJS console displays GET /account/%22[%7B/%22start/%22:/%222018-07-04T13:30:00/%22,/%22end/%22:/%222018-07-04T18:00:00/%22,/%22works/%22:[/%222/%22]%7D]%22 (1ms 404).
I also tried changing it to events: JSON.stringify(this.me.calendar), which still gave the GET request in console.
If I enter the array in the events on it's own, it is working. Also the console.log inside the events function is returning the same array.
Is there a way for me to simply enter my array for FullCalendar, or do I have to make it get the JSON from an URL?
I managed to solve the issue by changing the let events inside of my events function to let events = that.me.calendar ? JSON.parse(that.me.calendar) : []; and now the events are being displayed.

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.

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.

Categories

Resources